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

updated the util files and test #665

Merged
merged 1 commit into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
46 changes: 41 additions & 5 deletions pkgs/swarmauri/swarmauri/utils/base64_to_img_url.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,44 @@
import base64
from PIL import Image
from io import BytesIO
import requests
from typing import Union

def base64_to_img_url(base64_str: str) -> str:
# Placeholder - needs external API to upload and get URL
raise NotImplementedError("Upload the decoded image to a server and return the URL")

def base64_to_img_url(base64_str: str, api_key: str) -> str:
"""
Convert a base64 encoded image string to a URL by uploading to ImgBB.
Get your IMGBB API key from: https://api.imgbb.com/

Args:
base64_str (str): The base64 encoded image string.
api_key (str): The ImgBB API key.

Returns:
str: The URL of the uploaded image.

Raises:
Exception: If the upload fails.
"""
# ImgBB API endpoint
url = "https://api.imgbb.com/1/upload"

# Prepare the payload
payload = {
"key": api_key,
"image": base64_str,
}

# Send POST request to ImgBB API
response = requests.post(url, payload)

# Check if the request was successful
if response.status_code == 200:
data = response.json()
if data["success"]:
return data["data"]["url"]
else:
raise Exception(
"Failed to upload image: "
+ data.get("error", {}).get("message", "Unknown error")
)
else:
raise Exception(f"Failed to upload image. Status code: {response.status_code}")
1 change: 1 addition & 0 deletions pkgs/swarmauri/swarmauri/utils/file_path_to_base64.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from PIL import Image
from io import BytesIO


def file_path_to_base64(file_path: str) -> str:
image = Image.open(file_path)
buffered = BytesIO()
Expand Down
45 changes: 42 additions & 3 deletions pkgs/swarmauri/swarmauri/utils/file_path_to_img_url.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,45 @@
import requests
import base64
from typing import Union
from PIL import Image

def file_path_to_img_url(file_path: str) -> str:
# Placeholder - needs external API to upload and get URL
raise NotImplementedError("Upload the image file to a server and return the URL")

def file_path_to_img_url(file_path: str, api_key: str) -> str:
"""
Convert an image in a specified path to a URL by uploading to ImgBB.
Get your IMGBB API key from: https://api.imgbb.com/

Args:
file_path (str): The path of the image.
api_key (str): The ImgBB API key.

Returns:
str: The URL of the uploaded image.

Raises:
Exception: If the upload fails.
"""
url = "https://api.imgbb.com/1/upload"

# Open and encode the image file
with open(file_path, "rb") as file:
payload = {
"key": api_key,
"image": base64.b64encode(file.read()),
}

# Send POST request to ImgBB API
response = requests.post(url, payload)

# Check if the request was successful
if response.status_code == 200:
data = response.json()
if data["success"]:
return data["data"]["url"]
else:
raise Exception(
"Failed to upload image: "
+ data.get("error", {}).get("message", "Unknown error")
)
else:
raise Exception(f"Failed to upload image. Status code: {response.status_code}")
51 changes: 47 additions & 4 deletions pkgs/swarmauri/swarmauri/utils/in_memory_img_to_img_url.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,50 @@
import io
import base64
import requests
from PIL import Image
from typing import Union

def in_memory_img_to_img_url(image: Image.Image) -> str:
# Placeholder - needs external API to upload and get URL
# Example for Cloudinary or Imgur
raise NotImplementedError("Upload the image to an external server and return the URL")

def in_memory_img_to_img_url(image: Image.Image, api_key: str) -> str:
"""
Convert an in-memory PIL Image to a URL by uploading to ImgBB.
Get your IMGBB API key from: https://api.imgbb.com/
Args:
image (Image.Image): The in-memory PIL Image.
api_key (str): The ImgBB API key.

Returns:
str: The URL of the uploaded image.

Raises:
Exception: If the upload fails.
"""
# ImgBB API endpoint
url = "https://api.imgbb.com/1/upload"

# Convert PIL Image to base64
buffered = io.BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()

# Prepare the payload
payload = {
"key": api_key,
"image": img_str,
}

# Send POST request to ImgBB API
response = requests.post(url, payload)

# Check if the request was successful
if response.status_code == 200:
data = response.json()
if data["success"]:
return data["data"]["url"]
else:
raise Exception(
"Failed to upload image: "
+ data.get("error", {}).get("message", "Unknown error")
)
else:
raise Exception(f"Failed to upload image. Status code: {response.status_code}")
Binary file added pkgs/swarmauri/tests/static/cityscape.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added pkgs/swarmauri/tests/static/generated_image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added pkgs/swarmauri/tests/static/generated_image_0.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added pkgs/swarmauri/tests/static/generated_image_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added pkgs/swarmauri/tests/static/generated_image_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added pkgs/swarmauri/tests/static/sunset.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions pkgs/swarmauri/tests/unit/llms/GroqAIAudio_unit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def test_audio_transcription(groqai_model, model_name):
model.name = model_name

prediction = model.predict(
audio_path="./tests/unit/llms/static/audio/test.mp3",
audio_path="pkgs/swarmauri/tests/static/test.mp3",
)

logging.info(prediction)
Expand All @@ -63,7 +63,7 @@ def test_audio_translation(groqai_model):
model.name = "whisper-large-v3"

prediction = model.predict(
audio_path="./tests/unit/llms/static/audio/test_fr.mp3",
audio_path="pkgs/swarmauri/tests/static/test_fr.mp3",
task="translation",
)

Expand Down
2 changes: 1 addition & 1 deletion pkgs/swarmauri/tests/unit/llms/OpenAIAudioTTS_unit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
load_dotenv()

API_KEY = os.getenv("OPENAI_API_KEY")
file_path = "pkgs/swarmauri/tests/unit/llms/static/audio/test_tts.mp3"
file_path = "pkgs/swarmauri/tests/static/test_tts.mp3"


@pytest.fixture(scope="module")
Expand Down
4 changes: 2 additions & 2 deletions pkgs/swarmauri/tests/unit/llms/OpenAIAudio_unit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from swarmauri.llms.concrete.OpenAIAudio import OpenAIAudio as LLM
from dotenv import load_dotenv

file_path = "pkgs/swarmauri/tests/unit/llms/static/audio/test.mp3"
file_path2 = "pkgs/swarmauri/tests/unit/llms/static/audio/test_fr.mp3"
file_path = "pkgs/swarmauri/tests/static/test.mp3"
file_path2 = "pkgs/swarmauri/tests/static/test_fr.mp3"

load_dotenv()

Expand Down
42 changes: 32 additions & 10 deletions pkgs/swarmauri/tests/unit/utils/base64_to_file_path_test.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,38 @@
import pytest
import base64
from PIL import Image
from io import BytesIO
import os
from swarmauri.utils.base64_to_file_path import base64_to_file_path # Adjust the path

@pytest.fixture
def mock_base64():
return 'iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAA...'
# Import the function to be tested
from swarmauri.utils.base64_to_file_path import base64_to_file_path


@pytest.fixture
def mock_file_path(tmp_path):
return os.path.join(tmp_path, 'test_image.jpg')
def sample_image():
# Create a simple 10x10 red image
image = Image.new("RGB", (10, 10), color="red")
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode()


def test_base64_to_file_path(sample_image, tmp_path):
# Create a temporary file path
file_path = tmp_path / "test_image.png"

# Call the function
base64_to_file_path(sample_image, str(file_path))

# Check if the file exists
assert file_path.exists()

# Open the saved image
saved_image = Image.open(file_path)

# Check if the image has the correct size and color
assert saved_image.size == (10, 10)
assert saved_image.getpixel((5, 5)) == (255, 0, 0) # Red color

@pytest.mark.unit
def test_base64_to_file_path(mock_base64, mock_file_path):
base64_to_file_path(mock_base64, mock_file_path)
assert os.path.exists(mock_file_path)
# Clean up
saved_image.close()
51 changes: 39 additions & 12 deletions pkgs/swarmauri/tests/unit/utils/base64_to_img_url_test.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,45 @@
import pytest
import os
import base64
from swarmauri.utils.base64_to_img_url import base64_to_img_url # Adjust the path
import requests
from PIL import Image
from dotenv import load_dotenv
from swarmauri.utils.base64_to_img_url import base64_to_img_url

@pytest.fixture
def mock_base64():
return base64.b64encode(b'test image data').decode('utf-8')
# Load environment variables
load_dotenv()

@pytest.fixture
def mock_upload_url():
return 'https://mockserver.com/upload'
# Get API key from environment variable
API_KEY = os.getenv("IMGBB_API_KEY")

# Path to the test image
TEST_IMAGE_PATH = "pkgs/swarmauri/tests/static/cityscape.png"


@pytest.mark.skipif(
not API_KEY, reason="IMGBB_API_KEY is not set in the environment variables"
)
@pytest.mark.unit
def test_base64_to_img_url(mock_base64, mock_upload_url, requests_mock):
requests_mock.post(mock_upload_url, json={'url': 'https://mockserver.com/image.jpg'})
response = base64_to_img_url(mock_base64, mock_upload_url)
assert 'url' in response
assert response['url'] == 'https://mockserver.com/image.jpg'
def test_base64_to_img_url():
# Ensure the test image file exists
assert os.path.exists(TEST_IMAGE_PATH), f"Test image not found at {TEST_IMAGE_PATH}"

# Read the image file and encode it to base64
with open(TEST_IMAGE_PATH, "rb") as image_file:
base64_string = base64.b64encode(image_file.read()).decode()

# Call the function with the base64 string and API key
image_url = base64_to_img_url(
base64_str=base64_string,
api_key=API_KEY,
)

# Assert that we got a URL back
assert isinstance(image_url, str), "Expected a string URL, but got a different type"
assert image_url.startswith("http"), "Expected URL to start with 'http'"

# Optionally, check if the URL is accessible
response = requests.get(image_url)
assert (
response.status_code == 200
), f"Failed to access the uploaded image at {image_url}"
32 changes: 18 additions & 14 deletions pkgs/swarmauri/tests/unit/utils/file_path_to_base64_test.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import pytest
from swarmauri.utils.file_path_to_base64 import file_path_to_base64 # Adjust the path

@pytest.fixture
def mock_file_path(tmp_path):
file_path = tmp_path / "test_image.jpg"
with open(file_path, 'wb') as f:
f.write(b'test image data')
return file_path

@pytest.mark.unit
def test_file_path_to_base64(mock_file_path):
img_base64 = file_path_to_base64(mock_file_path)
assert isinstance(img_base64, str)
assert img_base64.startswith('iVBOR') # Checking for common base64 header
import base64
from swarmauri.utils.file_path_to_base64 import file_path_to_base64

test_image_path = "pkgs/swarmauri/tests/static/cityscape.png"


def test_file_path_to_base64():
# Call the function to get the base64 result
result = file_path_to_base64(test_image_path)

# Manually load the image and convert it to base64 to compare
with open(test_image_path, "rb") as img_file:
expected = base64.b64encode(img_file.read()).decode("utf-8")

# Assert the result is the expected base64 string
assert (
result == expected
), "Base64 conversion of the image does not match the expected output."
50 changes: 34 additions & 16 deletions pkgs/swarmauri/tests/unit/utils/file_path_to_img_url_test.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
import pytest
from swarmauri.utils.file_path_to_img_url import file_path_to_img_url # Adjust the path
import os
import requests
from swarmauri.utils.file_path_to_img_url import file_path_to_img_url
from dotenv import load_dotenv

@pytest.fixture
def mock_file_path(tmp_path):
return tmp_path / "test_image.jpg"
# Load environment variables
load_dotenv()

@pytest.fixture
def mock_upload_url():
return 'https://mockserver.com/upload'
# Get API key from environment variable
API_KEY = os.getenv("IMGBB_API_KEY")

# Path to the test image
TEST_IMAGE_PATH = "pkgs/swarmauri/tests/static/cityscape.png"


@pytest.mark.skipif(
not API_KEY, reason="IMGBB_API_KEY is not set in the environment variables"
)
@pytest.mark.unit
def test_file_path_to_img_url(mock_file_path, mock_upload_url, requests_mock):
# Create a dummy file
with open(mock_file_path, 'wb') as f:
f.write(b'test image data')

requests_mock.post(mock_upload_url, json={'url': 'https://mockserver.com/image.jpg'})
response = file_path_to_img_url(mock_file_path, mock_upload_url)
assert 'url' in response
assert response['url'] == 'https://mockserver.com/image.jpg'
def test_file_path_to_img_url():
# Ensure the test image file exists
assert os.path.exists(TEST_IMAGE_PATH), f"Test image not found at {TEST_IMAGE_PATH}"

# Call the function with the real API key and image file
image_url = file_path_to_img_url(
file_path=TEST_IMAGE_PATH,
api_key=API_KEY,
)

# Assert that we got a URL back
assert isinstance(image_url, str), "Expected a string URL, but got a different type"
assert image_url.startswith("http"), "Expected URL to start with 'http'"

# Optionally, check if the URL is accessible
response = requests.get(image_url)
assert (
response.status_code == 200
), f"Failed to access the uploaded image at {image_url}"
Loading