返回提交历史
Modified
g4f/gui/server/backend_api.py
+3
-1
Modified
g4f/image/copy_images.py
+15
-14
XFEstudio/gpt4free
Add user log
4337fa7f
代码差异
2 个文件
+18
-15
@@ -39,6 +39,7 @@ from ...cookies import get_cookies_dir
39
39
from ...image.copy_images import secure_filename, get_source_url, get_media_dir, copy_media
40
40
from ... import ChatCompletion
41
41
from ... import models
42
from ... import debug
42
43
from .api import Api
43
44
44
45
logger = logging.getLogger(__name__)
@@ -132,6 +133,7 @@ class Backend_Api(Api):
132
133
json_data["provider"] = random.choice(models.demo_models[model][1])
133
134
else:
134
135
json_data["provider"] = models.HuggingFace
136
debug.log("User:", request.headers)
135
137
kwargs = self._prepare_conversation_kwargs(json_data)
136
138
return self.app.response_class(
137
139
self._create_response_stream(
@@ -352,7 +354,7 @@ class Backend_Api(Api):
352
354
suffix = os.path.splitext(filename)[1].lower()
353
355
copyfile = get_tempfile(file, suffix)
354
356
result = None
355
if has_markitdown:
357
if has_markitdown and not filename.endswith((".md", ".json")):
356
358
try:
357
359
language = request.headers.get("x-recognition-language")
358
360
md = MarkItDown()
@@ -55,6 +55,12 @@ def get_source_url(image: str, default: str = None) -> str:
55
55
return decoded_url
56
56
return default
57
57
58
def get_target_path(response, filename: str) -> str:
59
date = response.headers.get("last-modified", response.headers.get("date"))
60
timestamp = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z').timestamp()
61
filename = str(int(timestamp)) + "_" + filename.split("_", maxsplit=1)[-1]
62
return os.path.join(get_media_dir(), filename)
63
58
64
async def save_response_media(response, prompt: str, tags: list[str]) -> AsyncIterator:
59
65
"""Save media from response to local file and return URL"""
60
66
if isinstance(response, str):
@@ -65,7 +71,7 @@ async def save_response_media(response, prompt: str, tags: list[str]) -> AsyncIt
65
71
raise ValueError(f"Unsupported media type: {content_type}")
66
72
67
73
filename = get_filename(tags, prompt, f".{extension}", prompt)
68
target_path = os.path.join(get_media_dir(), filename)
74
target_path = get_target_path(response, filename)
69
75
ensure_media_dir()
70
76
with open(target_path, 'wb') as f:
71
77
if isinstance(response, bytes):
@@ -158,12 +164,8 @@ async def copy_media(
158
164
# Use aiohttp to fetch the image
159
165
async with session.get(image, ssl=request_ssl, headers=request_headers) as response:
160
166
response.raise_for_status()
161
date = response.headers.get("last-modified", response.headers.get("date"))
162
if date and target_path != target:
163
timestamp = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z').timestamp()
164
filename = str(int(timestamp)) + "_" + filename.split("_", maxsplit=1)[-1]
165
target_path = os.path.join(get_media_dir(), filename)
166
debug.log(f"Copying image: {image} to {target_path}")
167
if target is None:
168
target_path = get_target_path(response, filename)
167
169
media_type = response.headers.get("content-type", "application/octet-stream")
168
170
if media_type not in ("application/octet-stream", "binary/octet-stream"):
169
171
if media_type not in MEDIA_TYPE_MAP:
@@ -180,11 +182,10 @@ async def copy_media(
180
182
file_header = f.read(12)
181
183
try:
182
184
detected_type = is_accepted_format(file_header)
183
if detected_type:
184
media_extension = f".{detected_type.split('/')[-1]}"
185
media_extension = media_extension.replace("jpeg", "jpg")
186
os.rename(target_path, f"{target_path}{media_extension}")
187
target_path = f"{target_path}{media_extension}"
185
media_extension = f".{detected_type.split('/')[-1]}"
186
media_extension = media_extension.replace("jpeg", "jpg")
187
os.rename(target_path, f"{target_path}{media_extension}")
188
target_path = f"{target_path}{media_extension}"
188
189
except ValueError:
189
190
pass
190
191
# Build URL with safe encoding
@@ -192,9 +193,9 @@ async def copy_media(
192
193
return f"/media/{url_filename}" + ('?' + (add_url if isinstance(add_url, str) else '' + 'url=' + quote(image)) if add_url and not image.startswith('data:') else '')
193
194
194
195
except (ClientError, IOError, OSError, ValueError) as e:
195
debug.error(f"Image copying failed: {type(e).__name__}: {e}")
196
debug.error(f"Image copying failed:", e)
196
197
if target_path and os.path.exists(target_path):
197
198
os.unlink(target_path)
198
199
return get_source_url(image, image)
199
200
200
return await asyncio.gather(*[copy_image(img, target) for img in images])
201
return await asyncio.gather(*[copy_image(image, target) for image in images])