-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
fix(image): 修复openai图片data URI的MIME识别与编码链路 #7017
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
Closed
idiotsj
wants to merge
9
commits into
AstrBotDevs:master
from
idiotsj:codex/fix-6991-openai-mime-minimal
Closed
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
416ecf6
fix(openai): preserve image mime in data uri encoding (#6991)
idiotsj 9536cab
refactor(image): normalize file uri handling and test fixtures
idiotsj bbb0bf9
test: remove duplicated io image data uri test
idiotsj 9c9280f
fix(image): validate data uri and scheme; add jpeg gif coverage
idiotsj a0512ca
refactor(image): centralize default mime and clarify helper constraints
idiotsj 75888d4
refactor(image): simplify image source handling branches
idiotsj 2e9506f
refactor(image): align http scheme checks and remove dead branches
idiotsj 6333213
fix(image): narrow base64 decode error handling
idiotsj 7899320
fix(image): make base64 scheme matching case-insensitive
idiotsj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -8,6 +8,8 @@ | |||||||||||||
| import uuid | ||||||||||||||
| import zipfile | ||||||||||||||
| from pathlib import Path | ||||||||||||||
| from urllib.parse import unquote, urlsplit | ||||||||||||||
| from urllib.request import url2pathname | ||||||||||||||
|
|
||||||||||||||
| import aiohttp | ||||||||||||||
| import certifi | ||||||||||||||
|
|
@@ -206,6 +208,80 @@ def file_to_base64(file_path: str) -> str: | |||||||||||||
| return "base64://" + base64_str | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| DEFAULT_IMAGE_MIME_TYPE = "image/jpeg" | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def is_http_or_https_url(source: str) -> bool: | ||||||||||||||
| """Return whether source is a HTTP(S) URL (case-insensitive).""" | ||||||||||||||
| return urlsplit(source).scheme.lower() in ("http", "https") | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def detect_image_mime_type(data: bytes) -> str: | ||||||||||||||
| """根据图片二进制数据的 magic bytes 检测 MIME 类型。""" | ||||||||||||||
| if data[:8] == b"\x89PNG\r\n\x1a\n": | ||||||||||||||
| return "image/png" | ||||||||||||||
| if data[:2] == b"\xff\xd8": | ||||||||||||||
| return DEFAULT_IMAGE_MIME_TYPE | ||||||||||||||
| if data[:6] in (b"GIF87a", b"GIF89a"): | ||||||||||||||
| return "image/gif" | ||||||||||||||
| if data[:4] == b"RIFF" and data[8:12] == b"WEBP": | ||||||||||||||
| return "image/webp" | ||||||||||||||
| return DEFAULT_IMAGE_MIME_TYPE | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def image_source_to_data_uri(image_source: str) -> tuple[str, str]: | ||||||||||||||
| """将本地/内联图片来源统一转换为 data URI,并尽量保留真实 MIME 类型。 | ||||||||||||||
|
|
||||||||||||||
| 说明: | ||||||||||||||
| - 支持 `data:image/...`、`base64://...`、本地路径和 `file://...`。 | ||||||||||||||
| - 不支持远程 URL(`http://`、`https://`),调用方应先下载到本地文件。 | ||||||||||||||
| """ | ||||||||||||||
| lower_source = image_source.lower() | ||||||||||||||
|
|
||||||||||||||
| if lower_source.startswith("data:"): | ||||||||||||||
| prefix = image_source.split(",", 1)[0] | ||||||||||||||
| mime_type = prefix.split(";", 1)[0].removeprefix("data:").lower() | ||||||||||||||
| if not mime_type.startswith("image/"): | ||||||||||||||
| raise ValueError( | ||||||||||||||
| f"Only image data URI is supported, got MIME type: {mime_type or 'unknown'}", | ||||||||||||||
| ) | ||||||||||||||
| return image_source, mime_type | ||||||||||||||
|
|
||||||||||||||
| if is_http_or_https_url(image_source): | ||||||||||||||
| raise ValueError( | ||||||||||||||
| "Remote image URL is not supported in image_source_to_data_uri; download the file before calling this helper.", | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
| if image_source.startswith("base64://"): | ||||||||||||||
| raw_base64 = image_source.removeprefix("base64://") | ||||||||||||||
| mime_type = DEFAULT_IMAGE_MIME_TYPE | ||||||||||||||
| try: | ||||||||||||||
| image_bytes = base64.b64decode(raw_base64) | ||||||||||||||
| mime_type = detect_image_mime_type(image_bytes) | ||||||||||||||
| except Exception: | ||||||||||||||
| pass | ||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 在处理
Suggested change
|
||||||||||||||
| return f"data:{mime_type};base64,{raw_base64}", mime_type | ||||||||||||||
|
|
||||||||||||||
| if lower_source.startswith("file://"): | ||||||||||||||
| parsed = urlsplit(image_source) | ||||||||||||||
| if parsed.netloc and parsed.netloc != "localhost": | ||||||||||||||
| raw_path = f"//{parsed.netloc}{parsed.path}" | ||||||||||||||
| else: | ||||||||||||||
| raw_path = parsed.path | ||||||||||||||
| image_source = url2pathname(unquote(raw_path)) | ||||||||||||||
| elif "://" in image_source: | ||||||||||||||
| scheme = image_source.split("://", 1)[0].lower() | ||||||||||||||
| raise ValueError( | ||||||||||||||
| f"Unsupported image source scheme: {scheme}://", | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
| with open(image_source, "rb") as f: | ||||||||||||||
| image_bytes = f.read() | ||||||||||||||
| mime_type = detect_image_mime_type(image_bytes) | ||||||||||||||
| image_bs64 = base64.b64encode(image_bytes).decode("utf-8") | ||||||||||||||
| return f"data:{mime_type};base64,{image_bs64}", mime_type | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def get_local_ip_addresses(): | ||||||||||||||
| net_interfaces = psutil.net_if_addrs() | ||||||||||||||
| network_ips = [] | ||||||||||||||
|
|
||||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import base64 | ||
|
|
||
| PNG_BYTES = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" | ||
| GIF_BYTES = b"GIF89a\x01\x00\x01\x00\x80\x00\x00" | ||
| WEBP_BYTES = b"RIFF\x0c\x00\x00\x00WEBPVP8 " | ||
| JPEG_BYTES = b"\xff\xd8\xff\xe0\x00\x10JFIF" | ||
|
|
||
| PNG_BASE64 = base64.b64encode(PNG_BYTES).decode("ascii") | ||
| GIF_BASE64 = base64.b64encode(GIF_BYTES).decode("ascii") | ||
| WEBP_BASE64 = base64.b64encode(WEBP_BYTES).decode("ascii") | ||
| JPEG_BASE64 = base64.b64encode(JPEG_BYTES).decode("ascii") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.