Skip to content

images_upload_cli

Public accessible objects of that module.

image

Image processing and manipulation.

get_img_ext

get_img_ext(img: bytes) -> str

Get the extension of an image from a byte string.

Parameters:

Name Type Description Default
img bytes

A byte string representing an image.

required

Returns:

Type Description
str

The extension of the image file.

Source code in src/images_upload_cli/image.py
11
12
13
14
15
16
17
18
19
20
21
22
def get_img_ext(img: bytes) -> str:
    """Get the extension of an image from a byte string.

    Args:
        img: A byte string representing an image.

    Returns:
        The extension of the image file.
    """
    with BytesIO(img) as f:
        ext = Image.open(f).format
        return "" if ext is None else ext.lower()

get_font

get_font(size: int = 14) -> FreeTypeFont

Get font for thumbnail captions.

Parameters:

Name Type Description Default
size int

The size of the font. Defaults to 14.

14

Returns:

Type Description
FreeTypeFont

ImageFont.FreeTypeFont: Represents the font.

Source code in src/images_upload_cli/image.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def get_font(size: int = 14) -> ImageFont.FreeTypeFont:
    """Get font for thumbnail captions.

    Args:
        size: The size of the font. Defaults to 14.

    Returns:
        ImageFont.FreeTypeFont: Represents the font.
    """
    if font_name := getenv("CAPTION_FONT"):
        return ImageFont.truetype(font_name, size=size)

    default_fonts = [
        "Helvetica",
        "NotoSerif-Regular",
        "Menlo",
        "DejaVuSerif",
        "arial",
    ]
    return search_font(fonts=default_fonts, size=size)

search_font

search_font(fonts: list[str], size: int = 14) -> FreeTypeFont

Attempt to retrieve a TTF font from the system.

Parameters:

Name Type Description Default
fonts list[str]

A list of font names to search for.

required
size int

The font size. Defaults to 14.

14

Returns:

Type Description
FreeTypeFont

ImageFont.FreeTypeFont: Represents the font.

Raises:

Type Description
GetEnvError

If none of the default fonts are found.

Source code in src/images_upload_cli/image.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def search_font(fonts: list[str], size: int = 14) -> ImageFont.FreeTypeFont:
    """Attempt to retrieve a TTF font from the system.

    Args:
        fonts: A list of font names to search for.
        size: The font size. Defaults to 14.

    Returns:
        ImageFont.FreeTypeFont: Represents the font.

    Raises:
        GetEnvError: If none of the default fonts are found.
    """
    for font_name in fonts:
        try:
            return ImageFont.truetype(font_name, size=size)
        except OSError:  # noqa: PERF203
            continue

    msg = (
        f"None of the fonts were found: {fonts}.\n"
        f"Please setup CAPTION_FONT in environment variables or in '{get_config_path()}'.",
    )
    raise GetEnvError(msg)

make_thumbnail

make_thumbnail(img: bytes, font: FreeTypeFont, size: tuple[int, int] = (300, 300)) -> bytes

Generate thumbnail for the image.

Parameters:

Name Type Description Default
img bytes

The input image in bytes format.

required
font FreeTypeFont

The font to be used for the text caption.

required
size tuple[int, int]

The desired size of the thumbnail image. Defaults to (300, 300).

(300, 300)

Returns:

Type Description
bytes

The modified image in bytes format.

Source code in src/images_upload_cli/image.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def make_thumbnail(
    img: bytes,
    font: ImageFont.FreeTypeFont,
    size: tuple[int, int] = (300, 300),
) -> bytes:
    """Generate thumbnail for the image.

    Args:
        img: The input image in bytes format.
        font: The font to be used for the text caption.
        size: The desired size of the thumbnail image. Defaults to (300, 300).

    Returns:
        The modified image in bytes format.
    """
    # Open the input image and create a copy in RGB format.
    im = Image.open(BytesIO(img))
    pw = im.copy()

    if pw.mode != "RGB":
        pw = pw.convert("RGB")

    # Resize the image to the desired size using Lanczos resampling.
    pw.thumbnail(size=size, resample=Image.Resampling.LANCZOS)

    # Create a blank image for the text
    pw_with_line = Image.new(
        mode="RGB",
        size=(pw.width, pw.height + 16),
        color=(255, 255, 255),
    )
    pw_with_line.paste(pw, box=(0, 0))

    # Get the file size of the input image.
    fsize = human_size(len(img))

    # Draw the text caption
    d = ImageDraw.Draw(pw_with_line)
    d.text(
        xy=(pw.width / 5, pw.height),
        text=f"{im.width}x{im.height} ({im.format}) [{fsize}]",
        font=font,
        fill=(0, 0, 0),
    )

    # Save the modified image as a JPEG file in bytes format.
    buffer = BytesIO()
    pw_with_line.save(
        buffer,
        format="JPEG",
        quality=95,
        optimize=True,
        progressive=True,
    )

    return buffer.getvalue()

logger

Logger configuration.

ErrorHandler

ErrorHandler()

Bases: StreamHandler

Custom error handler for logging.

Source code in src/images_upload_cli/logger.py
12
13
14
15
def __init__(self: "ErrorHandler") -> None:
    """Init."""
    super().__init__()
    self.error_occurred = False

emit

emit(record: LogRecord) -> None

Emit a record.

Source code in src/images_upload_cli/logger.py
17
18
19
20
def emit(self: "ErrorHandler", record: logging.LogRecord) -> None:
    """Emit a record."""
    if record.levelno >= logging.ERROR:
        self.error_occurred = True

has_error_occurred

has_error_occurred() -> bool

Check if an error has occurred.

Source code in src/images_upload_cli/logger.py
22
23
24
def has_error_occurred(self: "ErrorHandler") -> bool:
    """Check if an error has occurred."""
    return self.error_occurred

setup_logger

setup_logger(log_level: str) -> ErrorHandler

Configure logger.

Parameters:

Name Type Description Default
log_level str

The log level to set for the logger.

required

Returns:

Name Type Description
ErrorHandler ErrorHandler

The error handler associated with the logger.

Source code in src/images_upload_cli/logger.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def setup_logger(log_level: str) -> ErrorHandler:
    """Configure logger.

    Args:
        log_level: The log level to set for the logger.

    Returns:
        ErrorHandler: The error handler associated with the logger.
    """
    logger.remove()
    # Console handler
    logger.add(
        sink=RichHandler(log_time_format="[%X]", rich_tracebacks=True),
        level=log_level,
        format=lambda _: "{message}",
    )
    # Error handler
    error_handler = ErrorHandler()
    logger.add(sink=error_handler, level="ERROR")

    return error_handler

main

Main logic for the images-upload-cli package.

upload_images async

upload_images(upload_func: Callable[[AsyncClient, bytes], Awaitable[str]], images: tuple[Path], thumbnail: bool) -> Sequence[tuple[str, str] | tuple[str, None]]

Upload images using the specified upload function and optionally generate thumbnails.

Parameters:

Name Type Description Default
upload_func Callable[[AsyncClient, bytes], Awaitable[str]]

The function used to upload the images.

required
images tuple[Path]

The paths of the images to be uploaded.

required
thumbnail bool

Indicates whether to generate thumbnails for the images.

required

Returns:

Type Description
Sequence[tuple[str, str] | tuple[str, None]]

The links to the uploaded images and their corresponding thumbnails.

Sequence[tuple[str, str] | tuple[str, None]]

The thumbnail link will be None if generation is disabled.

Source code in src/images_upload_cli/main.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
async def upload_images(
    upload_func: Callable[[AsyncClient, bytes], Awaitable[str]],
    images: tuple[Path],
    thumbnail: bool,
) -> Sequence[tuple[str, str] | tuple[str, None]]:
    """Upload images using the specified upload function and optionally generate thumbnails.

    Args:
        upload_func: The function used to upload the images.
        images: The paths of the images to be uploaded.
        thumbnail: Indicates whether to generate thumbnails for the images.

    Returns:
        The links to the uploaded images and their corresponding thumbnails.
        The thumbnail link will be `None` if generation is disabled.
    """
    links = []

    if thumbnail:
        font = get_font()

    async with AsyncClient() as client:
        for img_path in images:
            img = img_path.read_bytes()

            img_link = await upload_func(client, img)
            # If the upload fails, skip the current image and proceed with the next one.
            if not img_link:
                continue

            if thumbnail:
                thumb = make_thumbnail(img, font)  # pyright: ignore[reportPossiblyUnboundVariable]
                thumb_link = await upload_func(client, thumb)
                # If the upload fails, skip the current image and proceed with the next one.
                if not thumb_link:
                    continue
            else:
                thumb_link = None

            links.append((img_link, thumb_link))

    return links
format_link(links: Sequence[tuple[str, str] | tuple[str, None]], fmt: str) -> str

Format the image links based on the specified format.

Parameters:

Name Type Description Default
links Sequence[tuple[str, str] | tuple[str, None]]

The image links and their corresponding thumbnails.

required
fmt str

The format to use for formatting the links. Valid options are "plain", "bbcode", "html", and "markdown".

required

Returns:

Type Description
str

The formatted image links as a string.

Source code in src/images_upload_cli/main.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def format_link(links: Sequence[tuple[str, str] | tuple[str, None]], fmt: str) -> str:
    """Format the image links based on the specified format.

    Args:
        links: The image links and their corresponding thumbnails.
        fmt: The format to use for formatting the links. Valid options are "plain", "bbcode", "html", and "markdown".

    Returns:
        The formatted image links as a string.
    """
    if fmt == "plain":
        return " ".join([img_link for img_link, _ in links])

    if fmt == "bbcode":
        return " ".join(
            f"[img]{img_link}[/img]"
            if thumb_link is None
            else f"[url={img_link}][img]{thumb_link}[/img][/url]"
            for img_link, thumb_link in links
        )

    if fmt == "html":
        return " ".join(
            f'<img src="{img_link}" alt="image">'
            if thumb_link is None
            else f'<a href="{img_link}"><img src="{thumb_link}" alt="thumb"></a>'
            for img_link, thumb_link in links
        )

    if fmt == "markdown":
        return " ".join(
            f"![image]({img_link})"
            if thumb_link is None
            else f"[![thumb]({thumb_link})]({img_link})"
            for img_link, thumb_link in links
        )

    return ""

upload

Upload images to various hosting services.

anhmoe_upload async

anhmoe_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the anh.mo.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@logger.catch(default="")
async def anhmoe_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `anh.mo`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = "anh.moe_public_api"

    response = await client.post(
        url="https://anh.moe/api/1/upload",
        data={"key": key},
        files={"source": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["image"]["url"]

beeimg_upload async

beeimg_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the beeimg.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@logger.catch(default="")
async def beeimg_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `beeimg.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    ext = get_img_ext(img)
    name = f"img.{ext}"
    content_type = f"image/{ext}"

    response = await client.post(
        url="https://beeimg.com/api/upload/file/json/",
        files={"file": (name, img, content_type)},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return f"https:{response.json()['files']['url']}"

catbox_upload async

catbox_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the catbox.moe.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@logger.catch(default="")
async def catbox_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `catbox.moe`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    response = await client.post(
        url="https://catbox.moe/user/api.php",
        data={"reqtype": "fileupload"},
        files={"fileToUpload": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.text

fastpic_upload async

fastpic_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the fastpic.org.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@logger.catch(default="")
async def fastpic_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `fastpic.org`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    response = await client.post(
        url="https://fastpic.org/upload?api=1",
        data={
            "method": "file",
            "check_thumb": "no",
            "uploading": "1",
        },
        files={"file1": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    match = search(r"<imagepath>(.+?)</imagepath>", response.text)
    if match is None:
        logger.error(f"Image link not found in '{response.url}' response.")
        logger.debug(f"Response text:\n{response.text}")
        return ""

    return match[1].strip()

filecoffee_upload async

filecoffee_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the file.coffee.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
@logger.catch(default="")
async def filecoffee_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `file.coffee`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    response = await client.post(
        url="https://file.coffee/api/file/upload",
        files={"file": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["url"]

freeimage_upload async

freeimage_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the freeimage.host.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@logger.catch(default="")
async def freeimage_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `freeimage.host`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("FREEIMAGE_KEY")

    response = await client.post(
        url="https://freeimage.host/api/1/upload",
        data={"key": key},
        files={"source": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["image"]["url"]

gyazo_upload async

gyazo_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the gyazo.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
@logger.catch(default="")
async def gyazo_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `gyazo.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("GYAZO_TOKEN")

    response = await client.post(
        url=f"https://upload.gyazo.com/api/upload?access_token={key}",
        files={"imagedata": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["url"]

imageban_upload async

imageban_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the imageban.ru.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
@logger.catch(default="")
async def imageban_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `imageban.ru`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    token = get_env("IMAGEBAN_TOKEN")

    response = await client.post(
        url="https://api.imageban.ru/v1",
        headers={"Authorization": f"TOKEN {token}"},
        files={"image": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["data"]["link"]

imagebin_upload async

imagebin_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the imagebin.ca.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
@logger.catch(default="")
async def imagebin_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `imagebin.ca`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    response = await client.post(
        url="https://imagebin.ca/upload.php",
        files={"file": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    match = search(r"url:(.+?)$", response.text)
    if match is None:
        logger.error(f"Image link not found in '{response.url}' response.")
        logger.debug(f"Response text:\n{response.text}")
        return ""

    return match[1].strip()

imgbb_upload async

imgbb_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the imgbb.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
@logger.catch(default="")
async def imgbb_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `imgbb.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("IMGBB_KEY")

    response = await client.post(
        url="https://api.imgbb.com/1/upload",
        data={"key": key},
        files={"image": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["data"]["url"]

imgchest_upload async

imgchest_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the imgchest.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
@logger.catch(default="")
async def imgchest_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `imgchest.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("IMGCHEST_KEY")
    name = f"img.{get_img_ext(img)}"

    response = await client.post(
        url="https://api.imgchest.com/v1/post",
        headers={"Authorization": f"Bearer {key}"},
        files={"images[]": (name, img)},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["data"]["images"][0]["link"]

imgur_upload async

imgur_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the imgur.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
@logger.catch(default="")
async def imgur_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `imgur.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    client_id = getenv("IMGUR_CLIENT_ID", "dd32dd3c6aaa9a0")

    response = await client.post(
        url="https://api.imgur.com/3/image",
        headers={"Authorization": f"Client-ID {client_id}"},
        files={"image": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["data"]["link"]

lensdump_upload async

lensdump_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the lensdump.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
@logger.catch(default="")
async def lensdump_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `lensdump.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("LENSDUMP_KEY")

    response = await client.post(
        url="https://lensdump.com/api/1/upload",
        data={"key": key},
        files={"source": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["image"]["url"]

pixeldrain_upload async

pixeldrain_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the pixeldrain.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
@logger.catch(default="")
async def pixeldrain_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `pixeldrain.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("PIXELDRAIN_KEY")

    response = await client.post(
        url="https://pixeldrain.com/api/file",
        auth=BasicAuth(username="", password=key),
        files={"file": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return f"https://pixeldrain.com/api/file/{response.json()['id']}"

pixhost_upload async

pixhost_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the pixhost.to.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
@logger.catch(default="")
async def pixhost_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `pixhost.to`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    response = await client.post(
        url="https://api.pixhost.to/images",
        data={"content_type": 0},
        files={"img": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    show_url = response.json()["show_url"]

    # Get direct link.
    get_resp = await client.get(show_url)
    u = urlparse(show_url)
    match = search(
        rf"({u.scheme}://(.+?){u.netloc}/images/{u.path.removeprefix('/show/')})",
        get_resp.text,
    )
    image_link = None if match is None else match[0].strip()

    return show_url if image_link is None else image_link

ptpimg_upload async

ptpimg_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the ptpimg.me.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
@logger.catch(default="")
async def ptpimg_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `ptpimg.me`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("PTPIMG_KEY")

    response = await client.post(
        url="https://ptpimg.me/upload.php",
        data={"api_key": key},
        files={"file-upload[0]": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return f"https://ptpimg.me/{response.json()[0]['code']}.{response.json()[0]['ext']}"

smms_upload async

smms_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the sm.ms.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
@logger.catch(default="")
async def smms_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `sm.ms`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("SMMS_KEY")

    response = await client.post(
        url="https://sm.ms/api/v2/upload",
        headers={"Authorization": key},
        files={"smfile": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    json = response.json()

    return json["images"] if json["code"] == "image_repeated" else json["data"]["url"]

sxcu_upload async

sxcu_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the sxcu.net.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
@logger.catch(default="")
async def sxcu_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `sxcu.net`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    response = await client.post(
        url="https://sxcu.net/api/files/create",
        headers={"user-agent": "python-https/1.0.0"},
        files={"file": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return f"{response.json()['url']}.{get_img_ext(img)}"

telegraph_upload async

telegraph_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the telegra.ph.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
@logger.catch(default="")
async def telegraph_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `telegra.ph`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    response = await client.post(
        url="https://telegra.ph/upload",
        files={"file": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return f"https://telegra.ph{response.json()[0]['src']}"

thumbsnap_upload async

thumbsnap_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the thumbsnap.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
@logger.catch(default="")
async def thumbsnap_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `thumbsnap.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("THUMBSNAP_KEY")

    response = await client.post(
        url="https://thumbsnap.com/api/upload",
        data={"key": key},
        files={"media": img},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["data"]["media"]

tixte_upload async

tixte_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the tixte.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
@logger.catch(default="")
async def tixte_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `tixte.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("TIXTE_KEY")
    name = f"img.{get_img_ext(img)}"

    response = await client.post(
        url="https://api.tixte.com/v1/upload",
        headers={"Authorization": key},
        data={"payload_json": '{"random":true}'},
        files={"file": (name, img)},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["data"]["direct_url"]

up2sha_upload async

up2sha_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the up2sha.re.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
@logger.catch(default="")
async def up2sha_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `up2sha.re`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("UP2SHA_KEY")
    ext = get_img_ext(img)
    name = f"img.{ext}"

    response = await client.post(
        url="https://api.up2sha.re/files",
        headers={"X-Api-Key": key},
        files={"file": (name, img)},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return f"{response.json()['public_url'].replace('file?f=', 'media/raw/')}.{ext}"

uplio_upload async

uplio_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the upl.io.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
@logger.catch(default="")
async def uplio_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `upl.io`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("UPLIO_KEY")
    ext = get_img_ext(img)
    name = f"img.{ext}"

    response = await client.post(
        url="https://upl.io",
        data={"key": key},
        files={"file": (name, img)},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    host, uid = response.text.rsplit("/", 1)
    return f"{host}/i/{uid}.{ext}"

uploadcare_upload async

uploadcare_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the uploadcare.com.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
@logger.catch(default="")
async def uploadcare_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `uploadcare.com`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("UPLOADCARE_KEY")
    name = f"img.{get_img_ext(img)}"

    response = await client.post(
        url="https://upload.uploadcare.com/base/",
        data={
            "UPLOADCARE_PUB_KEY": key,
            "UPLOADCARE_STORE": "1",
        },
        files={"filename": (name, img)},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return f"https://ucarecdn.com/{response.json()['filename']}/{name}"

vgy_upload async

vgy_upload(client: AsyncClient, img: bytes) -> str

Uploads an image to the vgy.me.

Parameters:

Name Type Description Default
client AsyncClient

The async HTTP client used to make the API request.

required
img bytes

The image data to be uploaded.

required

Returns:

Type Description
str

The URL of the uploaded image, or an empty string if the upload failed.

Source code in src/images_upload_cli/upload.py
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
@logger.catch(default="")
async def vgy_upload(client: AsyncClient, img: bytes) -> str:
    """Uploads an image to the `vgy.me`.

    Args:
        client: The async HTTP client used to make the API request.
        img: The image data to be uploaded.

    Returns:
        The URL of the uploaded image, or an empty string if the upload failed.
    """
    key = get_env("VGY_KEY")
    name = f"img.{get_img_ext(img)}"

    response = await client.post(
        url="https://vgy.me/upload",
        data={"userkey": key},
        files={"file[]": (name, img)},
    )
    if response.is_error:
        log_on_error(response)
        return ""

    return response.json()["image"]

util

Utility functions for the package.

GetEnvError

Bases: Exception

Exception raised when an environment variable is not found.

get_config_path

get_config_path() -> Path

Get the path to the app config file.

Returns:

Type Description
Path

The path to the app config file.

Source code in src/images_upload_cli/util.py
17
18
19
20
21
22
23
24
def get_config_path() -> Path:
    """Get the path to the app config file.

    Returns:
       The path to the app config file.
    """
    app_dir = click.get_app_dir("images-upload-cli")
    return Path(app_dir) / ".env"

get_env

get_env(variable: str) -> str

Get the value of an environment variable.

Parameters:

Name Type Description Default
variable str

The name of the environment variable to retrieve.

required

Returns:

Type Description
str

The value of the environment variable, if found.

Raises:

Type Description
GetEnvError

If the environment variable is not found.

Source code in src/images_upload_cli/util.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def get_env(variable: str) -> str:
    """Get the value of an environment variable.

    Args:
        variable: The name of the environment variable to retrieve.

    Returns:
        The value of the environment variable, if found.

    Raises:
        GetEnvError: If the environment variable is not found.
    """
    if value := getenv(variable):
        return value

    msg = f"Please setup {variable} in environment variables or in '{get_config_path()}'."
    raise GetEnvError(msg)

human_size

human_size(num: float, suffix: str = 'B') -> str

Convert bytes to human-readable format.

Parameters:

Name Type Description Default
num float

The number of bytes to be converted.

required
suffix str

The suffix to be appended to the converted size.

'B'

Returns:

Type Description
str

The human-readable size with the appropriate unit and suffix.

Source code in src/images_upload_cli/util.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def human_size(num: float, suffix: str = "B") -> str:
    """Convert bytes to human-readable format.

    Args:
        num: The number of bytes to be converted.
        suffix: The suffix to be appended to the converted size.

    Returns:
        The human-readable size with the appropriate unit and suffix.
    """
    units = ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]
    round_num = 1024.0

    for unit in units:
        if abs(num) < round_num:
            return f"{num:3.1f} {unit}{suffix}"
        num /= round_num

    return f"{num:.1f} Yi{suffix}"

notify_send

notify_send(text_to_print: str) -> None

Send desktop notifications via libnotify.

Parameters:

Name Type Description Default
text_to_print str

The text to be displayed in the desktop notification.

required
Source code in src/images_upload_cli/util.py
67
68
69
70
71
72
73
74
def notify_send(text_to_print: str) -> None:
    """Send desktop notifications via libnotify.

    Args:
        text_to_print: The text to be displayed in the desktop notification.
    """
    if notify_send := which("notify-send"):
        Popen([notify_send, "-a", "images-upload-cli", text_to_print])  # noqa: S603

log_on_error

log_on_error(response: Response) -> None

Logs an error message based on the HTTP response.

Parameters:

Name Type Description Default
response Response

The HTTP response object.

required
Source code in src/images_upload_cli/util.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def log_on_error(response: Response) -> None:
    """Logs an error message based on the HTTP response.

    Args:
        response: The HTTP response object.
    """
    status_class = response.status_code // 100
    error_types = {
        1: "Informational response",
        3: "Redirect response",
        4: "Client error",
        5: "Server error",
    }
    error_type = error_types.get(status_class, "Invalid status code")

    logger.error(
        f"{error_type} '{response.status_code} {response.reason_phrase}' for url '{response.url}'."
    )
    logger.debug(f"Response text:\n{response.text}")