Skip to content

Commit

Permalink
Merge pull request #82 from computas/SP24-470-Create-endpoint-sending…
Browse files Browse the repository at this point in the history
…-three-images-of-a-specific-label

Sp24 470 create endpoint sending three images of a specific label
  • Loading branch information
sondrefj authored Jul 11, 2024
2 parents 10c49fe + 768c38c commit a4223c8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/webapp/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,20 @@ def view_high_score(json_data):
emit("viewHighScore", json.dumps(data), room=game_id)


@socketio.on("getExampleDrawings")
def get_example_drawings(json_data):
"""
Get example drawings from the database
"""
data = json.loads(json_data)
game_id = data["game_id"]
number_of_images = data["number_of_images"]
label = data["label"]
example_drawings = storage.get_n_random_images_from_label(
number_of_images, label)
emit("getExampleDrawings", json.dumps(example_drawings), room=game_id)


@socketio.on("classify")
def handle_classify(data, image, correct_label=None):
"""
Expand Down
31 changes: 29 additions & 2 deletions src/webapp/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from azure.storage.blob import BlobServiceClient
from utilities.keys import Keys
from utilities import setup
import random
import base64


def save_image(image, label, certainty):
Expand Down Expand Up @@ -96,11 +98,10 @@ def image_count():
return container_client.get_container_properties().metadata["image_count"]


def blob_connection():
def blob_connection(container_name=setup.CONTAINER_NAME_NEW):
"""
Helper method for connection to blob service.
"""
container_name = setup.CONTAINER_NAME_NEW
connect_str = Keys.get("BLOB_CONNECTION_STRING")
try:
# Instantiate a BlobServiceClient using a connection string
Expand All @@ -115,3 +116,29 @@ def blob_connection():
raise Exception("Could not connect to blob client: " + str(e))

return container_client


def get_n_random_images_from_label(n, label):
"""
Returns n random images from the blob storage container with the given label.
"""
container_client = blob_connection(setup.CONTAINER_NAME_ORIGINAL)
blob_prefix = f"{label}/"
blobs = list(container_client.list_blobs(name_starts_with=blob_prefix))
selected_blobs = random.sample(blobs, min(n, len(blobs)))
images = []
for blob in selected_blobs:
blob_client = container_client.get_blob_client(blob)
image_data = blob_client.download_blob().readall()
decoded_image = image_to_data_url(
image_data, blob.content_settings.content_type)
images.append(decoded_image)
return images


def image_to_data_url(image_data, content_type):
"""
Converts image data to a data URL.
"""
base64_image = base64.b64encode(image_data).decode('utf-8')
return f"data:{content_type};base64,{base64_image}"

0 comments on commit a4223c8

Please sign in to comment.