XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Add image caching to Yupp provider

Introduces an image cache to avoid redundant uploads in the Yupp provider. Refactors media attachment handling into a new prepare_files method, improving efficiency and code organization. Updates .gitignore to exclude .idea directory.

1c612433
Ammar <ammar.alkotb@gmail.com>
提交于

代码差异

2 个文件 +65 -35
Modified .gitignore +1 -0
@@ -9,3 +9,4 @@ g4f.egg-info
9 9 models/models.json
10 10 pyvenv.cfg
11 11 lib64
12 /.idea
Modified g4f/Provider/Yupp.py +64 -35
@@ -1,3 +1,4 @@
1 import hashlib
1 2 import json
2 3 import time
3 4 import uuid
@@ -22,6 +23,9 @@ from ..debug import log
22 23 YUPP_ACCOUNTS: List[Dict[str, Any]] = []
23 24 account_rotation_lock = asyncio.Lock()
24 25
26 # Global variables to manage Yupp Image Cache
27 ImagesCache:Dict[str, dict] = {}
28
25 29 class YuppAccount:
26 30 """Yupp account representation"""
27 31 def __init__(self, token: str, is_valid: bool = True, error_count: int = 0, last_used: float = 0):
@@ -202,6 +206,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
202 206 working = True
203 207 active_by_default = True
204 208 supports_stream = True
209 image_cache = True
205 210
206 211 @classmethod
207 212 def get_models(cls, api_key: str = None, **kwargs) -> List[str]:
@@ -221,6 +226,59 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
221 226 cls.vision_models = [model.get("name") for model in models if "image/*" in model.get("supportedAttachmentMimeTypes", [])]
222 227 return cls.models
223 228
229 @classmethod
230 async def prepare_files(cls, media, session:aiohttp.ClientSession, account:Dict[str, ...])->list:
231 files = []
232 if not media:
233 return files
234 for file, name in media:
235 data = to_bytes(file)
236 hasher = hashlib.md5()
237 hasher.update(data)
238 image_hash = hasher.hexdigest()
239 file = ImagesCache.get(image_hash)
240 if cls.image_cache and file:
241 log_debug("Using cached image")
242 files.append(file)
243 continue
244 presigned_resp = await session.post(
245 "https://yupp.ai/api/trpc/chat.createPresignedURLForUpload?batch=1",
246 json={
247 "0": {"json": {"fileName": name, "fileSize": len(data), "contentType": is_accepted_format(data)}}},
248 headers={"Content-Type": "application/json",
249 "Cookie": f"__Secure-yupp.session-token={account['token']}"}
250 )
251 presigned_resp.raise_for_status()
252 upload_info = (await presigned_resp.json())[0]["result"]["data"]["json"]
253 upload_url = upload_info["signedUrl"]
254
255 await session.put(
256 upload_url,
257 data=data,
258 headers={
259 "Content-Type": is_accepted_format(data),
260 "Content-Length": str(len(data))
261 }
262 )
263
264 attachment_resp = await session.post(
265 "https://yupp.ai/api/trpc/chat.createAttachmentForUploadedFile?batch=1",
266 json={"0": {"json": {"fileName": name, "contentType": is_accepted_format(data),
267 "fileId": upload_info["fileId"]}}},
268 cookies={"__Secure-yupp.session-token": account["token"]}
269 )
270 attachment_resp.raise_for_status()
271 attachment = (await attachment_resp.json())[0]["result"]["data"]["json"]
272 file = {
273 "fileName": attachment["file_name"],
274 "contentType": attachment["content_type"],
275 "attachmentId": attachment["attachment_id"],
276 "chatMessageId": ""
277 }
278 ImagesCache[image_hash] = file
279 files.append(file)
280 return files
281
224 282 @classmethod
225 283 async def create_async_generator(
226 284 cls,
@@ -266,44 +324,15 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
266 324 try:
267 325 async with aiohttp.ClientSession() as session:
268 326 turn_id = str(uuid.uuid4())
269 files = []
327
270 328
271 329 # Handle media attachments
272 330 media = kwargs.get("media")
273 331 if media:
274 for file, name in list(merge_media(media, messages)):
275 data = to_bytes(file)
276 presigned_resp = await session.post(
277 "https://yupp.ai/api/trpc/chat.createPresignedURLForUpload?batch=1",
278 json={"0": {"json": {"fileName": name, "fileSize": len(data), "contentType": is_accepted_format(data)}}},
279 headers={"Content-Type": "application/json", "Cookie": f"__Secure-yupp.session-token={account['token']}"}
280 )
281 presigned_resp.raise_for_status()
282 upload_info = (await presigned_resp.json())[0]["result"]["data"]["json"]
283 upload_url = upload_info["signedUrl"]
284
285 await session.put(
286 upload_url,
287 data=data,
288 headers={
289 "Content-Type": is_accepted_format(data),
290 "Content-Length": str(len(data))
291 }
292 )
293
294 attachment_resp = await session.post(
295 "https://yupp.ai/api/trpc/chat.createAttachmentForUploadedFile?batch=1",
296 json={"0": {"json": {"fileName": name, "contentType": is_accepted_format(data), "fileId": upload_info["fileId"]}}},
297 cookies={"__Secure-yupp.session-token": account["token"]}
298 )
299 attachment_resp.raise_for_status()
300 attachment = (await attachment_resp.json())[0]["result"]["data"]["json"]
301 files.append({
302 "fileName": attachment["file_name"],
303 "contentType": attachment["content_type"],
304 "attachmentId": attachment["attachment_id"],
305 "chatMessageId": ""
306 })
332 media_ = list(merge_media(media, messages))
333 files = await cls.prepare_files(media_, session=session, account=account)
334 else:
335 files = []
307 336 mode = "image" if model in cls.image_models else "text"
308 337
309 338 # Build payload and URL - FIXED: Use consistent url_uuid handling
@@ -451,7 +480,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
451 480 match = line_pattern.match(line)
452 481 if not match:
453 482 continue
454
483
455 484 chunk_id, chunk_data = match.groups()
456 485 chunk_id = chunk_id.decode()
457 486