{"record":{"id":"5bd68023ce40ecb6","repo":"huggingface/transformers","slug":"incorrect-image-source-must-be-a-valid-url-starti","errorCode":null,"errorMessage":"Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got {image}. Failed with {e}","messagePattern":"Incorrect image source\\. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string\\. Got (.+?)\\. Failed with (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/transformers/image_utils.py","lineNumber":503,"sourceCode":"    \"\"\"\n    requires_backends(load_image, [\"vision\"])\n    if isinstance(image, str):\n        if image.startswith(\"http://\") or image.startswith(\"https://\"):\n            # We need to actually check for a real protocol, otherwise it's impossible to use a local file\n            # like http_huggingface_co.png\n            image = PIL.Image.open(BytesIO(httpx.get(image, timeout=timeout, follow_redirects=True).content))\n        elif os.path.isfile(image):\n            image = PIL.Image.open(image)\n        else:\n            if image.startswith(\"data:image/\"):\n                image = image.split(\",\")[1]\n\n            # Try to load as base64\n            try:\n                b64 = base64.decodebytes(image.encode())\n                image = PIL.Image.open(BytesIO(b64))\n            except Exception as e:\n                raise ValueError(\n                    f\"Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got {image}. Failed with {e}\"\n                )\n    elif not isinstance(image, PIL.Image.Image):\n        raise TypeError(\n            \"Incorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image.\"\n        )\n    image = PIL.ImageOps.exif_transpose(image)\n    image = image.convert(\"RGB\")\n    return image\n\n\n@requires(backends=(\"torchvision\",))\ndef load_image_as_tensor(\n    image: Union[str, \"PIL.Image.Image\"],\n    timeout: float | None = None,\n) -> \"torch.Tensor\":\n    \"\"\"\n    Loads `image` directly to a `torch.Tensor` using torchvision.","sourceCodeStart":485,"sourceCodeEnd":521,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/image_utils.py#L485-L521","documentation":"Raised by `transformers.image_utils.load_image` when a string input is neither an http(s) URL (that branch fetches directly), nor an existing file path (os.path.isfile), and the final fallback — decoding it as base64 and opening it with PIL — throws. The caught exception `e` is appended, revealing the real cause (usually a binascii base64 error or PIL 'cannot identify image file'). The string was probably meant to be a path that doesn't exist or a malformed base64 payload.","triggerScenarios":"`load_image('/data/missing.jpg')` (typo'd or moved file); a relative path evaluated from the wrong working directory; a base64 string with whitespace/newlines or a broken 'data:image/...;base64,' prefix split; a corrupt/empty downloaded payload; a URL missing the scheme (treated as path, then base64).","commonSituations":"Datasets that moved or weren't downloaded; notebooks run from a different cwd so relative paths break; base64 copied from JSON with escaped characters; files with wrong extension or truncated transfers.","solutions":["Verify the path exists first: `os.path.isfile(path)`; check cwd if using relative paths.","For base64, ensure it is pure base64 (strip the 'data:image/...;base64,' prefix is handled, but remove whitespace/newlines) and that the bytes decode to a real image.","For URLs, confirm the scheme is http:// or https:// — scheme-less URLs fall into the file/base64 branches.","Inspect the appended `Failed with {e}` to see whether base64 decoding or PIL opening failed."],"exampleFix":"// before\nimg = load_image(\"./images/cat.jpg\")   # cwd changed -> not a file -> base64 fail\n\n// after\nimport os\npath = os.path.abspath(\"images/cat.jpg\")\nassert os.path.isfile(path), path\nimg = load_image(path)\n// base64 case:\nb64 = \"\".join(b64.split())             # strip whitespace\nimg = load_image(b64)","handlingStrategy":"try-catch","validationCode":"import os\n\ndef is_loadable_source(s: str) -> bool:\n    return s.startswith((\"http://\", \"https://\")) or os.path.isfile(s) or s.startswith(\"data:image/\")\n\nassert is_loadable_source(path_or_url), f\"not a URL, existing file, or data URI: {path_or_url}\"","typeGuard":null,"tryCatchPattern":"from transformers.image_utils import load_image\n\ntry:\n    img = load_image(src, timeout=10)\nexcept ValueError as e:\n    # retry once (e.g. transient FS sync), then fall back to another source\n    try:\n        img = load_image(fallback_src)\n    except ValueError:\n        raise RuntimeError(f\"could not load image source: {src}\") from e","preventionTips":["Resolve image paths to absolute paths at dataset-build time so cwd changes cannot break them.","Strip whitespace/newlines from base64 strings before passing them.","Validate downloaded datasets by checking file existence before preprocessing loops."],"tags":["image-processing","io","base64","file-path","loading"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}