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

XFEstudio/gpt4free

feat: enhance audio model handling and improve image URL resolution

- Updated `PollinationsAI` to exclude "gemini" model from `audio_models` - Added logic in `PollinationsAI` to expand `audio_models` with voices from `default_audio_model` - Appended voice names to `text_models` list in `PollinationsAI` if present in `default_audio_model` - Modified `PollinationsAI._generate_text` to inject `audio` parameters when a voice model is used - Updated `save_response_media` call to include voice name in model list - Changed `OpenaiChat.get_generated_image` to support both `file-service://` and `sediment://` URLs using `conversation_id` - Modified `OpenaiChat.create_messages` to optionally pass `prompt` - Adjusted `OpenaiChat.run` to determine `prompt` explicitly and set messages accordingly - Updated `OpenaiChat.iter_messages_line` to handle `None` in `fields.p` safely - Passed `prompt` and `conversation_id` to `OpenaiChat.get_generated_image` inside image parsing loop - Fixed redirect logic in `backend_api.py` to safely handle missing `skip` query param - Enhanced `render` function in `website.py` to support live file serving with `live` query param - Added new route `/dist/<path:name>` to serve static files from `DIST_DIR` in `website.py` - Adjusted `render` to include `.live` suffix in cache filename when applicable - Modified HTML replacements in `render` to preserve local `dist/` path if `add_origion` is True

8c3764df
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

4 个文件 +56 -19
Modified g4f/Provider/PollinationsAI.py +13 -2
@@ -105,9 +105,12 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
105 105 cls.audio_models = {
106 106 model.get("name"): model.get("voices")
107 107 for model in models
108 if "output_modalities" in model and "audio" in model["output_modalities"]
108 if "output_modalities" in model and "audio" in model["output_modalities"] and model.get("name") != "gemini"
109 109 }
110 110
111 if cls.default_audio_model in cls.audio_models:
112 cls.audio_models = {**cls.audio_models, **{voice: {} for voice in cls.audio_models[cls.default_audio_model]}}
113
111 114 # Create a set of unique text models starting with default model
112 115 unique_text_models = cls.text_models.copy()
113 116
@@ -120,6 +123,9 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
120 123 if model_name and "input_modalities" in model and "text" in model["input_modalities"]:
121 124 unique_text_models.append(model_name)
122 125
126 if cls.default_audio_model in cls.audio_models:
127 unique_text_models.extend([voice for voice in cls.audio_models[cls.default_audio_model]])
128
123 129 # Convert to list and update text_models
124 130 cls.text_models = list(dict.fromkeys(unique_text_models))
125 131
@@ -207,6 +213,11 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
207 213 "role": "user",
208 214 "content": prompt
209 215 }]
216 if model and model in cls.audio_models[cls.default_audio_model]:
217 kwargs["audio"] = {
218 "voice": model,
219 }
220 model = cls.default_audio_model
210 221 async for result in cls._generate_text(
211 222 model=model,
212 223 messages=messages,
@@ -359,6 +370,6 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
359 370 if finish_reason:
360 371 yield FinishReason(finish_reason)
361 372 else:
362 async for chunk in save_response_media(response, format_image_prompt(messages), [model]):
373 async for chunk in save_response_media(response, format_image_prompt(messages), [model, extra_parameters.get("audio", {}).get("voice")]):
363 374 yield chunk
364 375 return
Modified g4f/Provider/needs_auth/OpenaiChat.py +20 -9
@@ -254,16 +254,25 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
254 254 return messages
255 255
256 256 @classmethod
257 async def get_generated_image(cls, session: StreamSession, auth_result: AuthResult, element: dict, prompt: str = None) -> ImageResponse:
257 async def get_generated_image(cls, session: StreamSession, auth_result: AuthResult, element: dict, prompt: str, conversation_id: str) -> ImageResponse:
258 258 try:
259 259 prompt = element["metadata"]["dalle"]["prompt"]
260 file_id = element["asset_pointer"].split("file-service://", 1)[1]
260 except IndexError:
261 pass
262 try:
263 file_id = element["asset_pointer"]
264 if "file-service://" in file_id:
265 file_id = file_id.split("file-service://", 1)[-1]
266 url = f"{cls.url}/backend-api/files/{file_id}/download"
267 else:
268 file_id = file_id.split("sediment://")[-1]
269 url = f"{cls.url}/backend-api/conversation/{conversation_id}/attachment/{file_id}/download"
261 270 except TypeError:
262 271 return
263 272 except Exception as e:
264 raise RuntimeError(f"No Image: {e.__class__.__name__}: {e}")
273 raise RuntimeError(f"No Image: {element} - {e}")
265 274 try:
266 async with session.get(f"{cls.url}/backend-api/files/{file_id}/download", headers=auth_result.headers) as response:
275 async with session.get(url, headers=auth_result.headers) as response:
267 276 cls._update_request_args(auth_result, session)
268 277 await raise_for_status(response)
269 278 download_url = (await response.json())["download_url"]
@@ -285,6 +294,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
285 294 media: MediaListType = None,
286 295 return_conversation: bool = False,
287 296 web_search: bool = False,
297 prompt: str = None,
288 298 **kwargs
289 299 ) -> AsyncResult:
290 300 """
@@ -403,10 +413,11 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
403 413 if conversation.conversation_id is not None:
404 414 data["conversation_id"] = conversation.conversation_id
405 415 debug.log(f"OpenaiChat: Use conversation: {conversation.conversation_id}")
416 prompt = get_last_user_message(messages) if prompt is None else prompt
406 417 if action != "continue":
407 418 data["parent_message_id"] = getattr(conversation, "parent_message_id", conversation.message_id)
408 419 conversation.parent_message_id = None
409 messages = messages if conversation.conversation_id is None else [{"role": "user", "content": get_last_user_message(messages)}]
420 messages = messages if conversation.conversation_id is None else [{"role": "user", "content": prompt}]
410 421 data["messages"] = cls.create_messages(messages, image_requests, ["search"] if web_search else None)
411 422 headers = {
412 423 **cls._headers,
@@ -433,7 +444,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
433 444 await raise_for_status(response)
434 445 buffer = u""
435 446 async for line in response.iter_lines():
436 async for chunk in cls.iter_messages_line(session, auth_result, line, conversation, sources):
447 async for chunk in cls.iter_messages_line(session, auth_result, line, conversation, sources, prompt):
437 448 if isinstance(chunk, str):
438 449 chunk = chunk.replace("\ue203", "").replace("\ue204", "").replace("\ue206", "")
439 450 buffer += chunk
@@ -475,7 +486,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
475 486 yield FinishReason(conversation.finish_reason)
476 487
477 488 @classmethod
478 async def iter_messages_line(cls, session: StreamSession, auth_result: AuthResult, line: bytes, fields: Conversation, sources: Sources) -> AsyncIterator:
489 async def iter_messages_line(cls, session: StreamSession, auth_result: AuthResult, line: bytes, fields: Conversation, sources: Sources, prompt: str) -> AsyncIterator:
479 490 if not line.startswith(b"data: "):
480 491 return
481 492 elif line.startswith(b"data: [DONE]"):
@@ -490,7 +501,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
490 501 if line["type"] == "title_generation":
491 502 yield TitleGeneration(line["title"])
492 503 fields.p = line.get("p", fields.p)
493 if fields.p.startswith("/message/content/thoughts"):
504 if fields.p is not None and fields.p.startswith("/message/content/thoughts"):
494 505 if fields.p.endswith("/content"):
495 506 if fields.thoughts_summary:
496 507 yield Reasoning(token="", status=fields.thoughts_summary)
@@ -539,7 +550,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
539 550 generated_images = []
540 551 for element in c.get("parts"):
541 552 if isinstance(element, dict) and element.get("content_type") == "image_asset_pointer":
542 image = cls.get_generated_image(session, auth_result, element)
553 image = cls.get_generated_image(session, auth_result, element, prompt, fields.conversation_id)
543 554 generated_images.append(image)
544 555 for image_response in await asyncio.gather(*generated_images):
545 556 if image_response is not None:
Modified g4f/gui/server/backend_api.py +1 -1
@@ -360,7 +360,7 @@ class Backend_Api(Api):
360 360 if seed not in ["true", "True", "1"]:
361 361 random.seed(seed)
362 362 return redirect(f"/media/{random.choice(match_files)}"), 302
363 return redirect(f"/media/{match_files[int(request.args.get('skip', 0))]}", 302)
363 return redirect(f"/media/{match_files[int(request.args.get('skip') or 0)]}", 302)
364 364
365 365 @app.route('/backend-api/v2/upload_cookies', methods=['POST'])
366 366 def upload_cookies():
Modified g4f/gui/server/website.py +22 -7
@@ -3,28 +3,36 @@ from __future__ import annotations
3 3 import os
4 4 import requests
5 5 from datetime import datetime
6 from flask import send_from_directory, redirect
6 from flask import send_from_directory, redirect, request
7 7 from ...image.copy_images import secure_filename, get_media_dir, ensure_media_dir
8 8 from ...errors import VersionNotFoundError
9 9 from ... import version
10 10
11 11 GPT4FREE_URL = "https://gpt4free.github.io"
12 DIST_DIR = "./gpt4free.github.io/dist"
12 13
13 14 def redirect_home():
14 15 return redirect('/chat')
15 16
16 def render(filename = "chat"):
17 def render(filename = "chat", add_origion = True):
18 if request.args.get("live"):
19 add_origion = False
20 if os.path.exists(DIST_DIR):
21 path = os.path.abspath(os.path.join(os.path.dirname(DIST_DIR), (filename + ("" if "." in filename else ".html"))))
22 print( f"Debug mode: {path}")
23 return send_from_directory(os.path.dirname(path), os.path.basename(path))
17 24 try:
18 25 latest_version = version.utils.latest_version
19 26 except VersionNotFoundError:
20 27 latest_version = version.utils.current_version
21 28 today = datetime.today().strftime('%Y-%m-%d')
22 cache_file = os.path.join(get_media_dir(), f"{today}.{secure_filename(filename)}.{version.utils.current_version}-{latest_version}.html")
29 cache_file = os.path.join(get_media_dir(), f"{today}.{secure_filename(filename)}.{version.utils.current_version}-{latest_version}{'.live' if add_origion else ''}.html")
23 30 if not os.path.exists(cache_file):
24 31 ensure_media_dir()
25 32 html = requests.get(f"{GPT4FREE_URL}/{filename}.html").text
26 html = html.replace("../dist/", f"{GPT4FREE_URL}/dist/")
27 html = html.replace('"dist/', f"\"{GPT4FREE_URL}/dist/")
33 if add_origion:
34 html = html.replace("../dist/", f"dist/")
35 html = html.replace("\"dist/", f"\"{GPT4FREE_URL}/dist/")
28 36 with open(cache_file, 'w', encoding='utf-8') as f:
29 37 f.write(html)
30 38 return send_from_directory(os.path.abspath(get_media_dir()), os.path.basename(cache_file))
@@ -57,6 +65,10 @@ class Website:
57 65 'function': redirect_home,
58 66 'methods': ['GET', 'POST']
59 67 },
68 '/dist/<path:name>': {
69 'function': self._dist,
70 'methods': ['GET']
71 },
60 72 }
61 73
62 74 def _index(self, filename = "index"):
@@ -64,10 +76,13 @@ class Website:
64 76
65 77 def _qrcode(self, filename = "qrcode"):
66 78 return render(filename)
67
79
68 80 def _background(self, filename = "background"):
69 81 return render(filename)
70
82
71 83 def _chat(self, filename = "chat"):
72 84 filename = "chat/index" if filename == 'chat' else secure_filename(filename)
73 85 return render(filename)
86
87 def _dist(self, name: str):
88 return send_from_directory(os.path.abspath(DIST_DIR), name)