返回提交历史
Modified
g4f/gui/server/api.py
+11
-52
XFEstudio/gpt4free
feat(g4f/gui/server/api.py): enhance image handling and directory management
307c2e64
代码差异
1 个文件
+11
-52
@@ -2,12 +2,11 @@ from __future__ import annotations
2
2
3
3
import logging
4
4
import os
5
import os.path
6
5
import uuid
7
6
import asyncio
8
7
import time
9
8
from aiohttp import ClientSession
10
from typing import Iterator, Optional
9
from typing import Iterator, Optional, AsyncIterator, Union
11
10
from flask import send_from_directory
12
11
13
12
from g4f import version, models
@@ -20,21 +19,20 @@ from g4f.Provider import ProviderType, __providers__, __map__
20
19
from g4f.providers.base_provider import ProviderModelMixin, FinishReason
21
20
from g4f.providers.conversation import BaseConversation
22
21
23
conversations: dict[dict[str, BaseConversation]] = {}
22
# Define the directory for generated images
24
23
images_dir = "./generated_images"
25
24
25
# Function to ensure the images directory exists
26
def ensure_images_dir():
27
if not os.path.exists(images_dir):
28
os.makedirs(images_dir)
29
30
conversations: dict[dict[str, BaseConversation]] = {}
31
26
32
27
33
class Api:
28
34
@staticmethod
29
35
def get_models() -> list[str]:
30
"""
31
Return a list of all models.
32
33
Fetches and returns a list of all available models in the system.
34
35
Returns:
36
List[str]: A list of model names.
37
"""
38
36
return models._all_models
39
37
40
38
@staticmethod
@@ -82,9 +80,6 @@ class Api:
82
80
83
81
@staticmethod
84
82
def get_providers() -> list[str]:
85
"""
86
Return a list of all working providers.
87
"""
88
83
return {
89
84
provider.__name__: (
90
85
provider.label if hasattr(provider, "label") else provider.__name__
@@ -99,12 +94,6 @@ class Api:
99
94
100
95
@staticmethod
101
96
def get_version():
102
"""
103
Returns the current and latest version of the application.
104
105
Returns:
106
dict: A dictionary containing the current and latest version.
107
"""
108
97
try:
109
98
current_version = version.utils.current_version
110
99
except VersionNotFoundError:
@@ -115,18 +104,10 @@ class Api:
115
104
}
116
105
117
106
def serve_images(self, name):
107
ensure_images_dir()
118
108
return send_from_directory(os.path.abspath(images_dir), name)
119
109
120
110
def _prepare_conversation_kwargs(self, json_data: dict, kwargs: dict):
121
"""
122
Prepares arguments for chat completion based on the request data.
123
124
Reads the request and prepares the necessary arguments for handling
125
a chat completion request.
126
127
Returns:
128
dict: Arguments prepared for chat completion.
129
"""
130
111
model = json_data.get('model') or models.default
131
112
provider = json_data.get('provider')
132
113
messages = json_data['messages']
@@ -159,13 +140,11 @@ class Api:
159
140
result = ChatCompletion.create(**kwargs)
160
141
first = True
161
142
if isinstance(result, ImageResponse):
162
# Якщо результат є ImageResponse, обробляємо його як одиночний елемент
163
143
if first:
164
144
first = False
165
145
yield self._format_json("provider", get_last_provider(True))
166
146
yield self._format_json("content", str(result))
167
147
else:
168
# Якщо результат є ітерабельним, обробляємо його як раніше
169
148
for chunk in result:
170
149
if first:
171
150
first = False
@@ -181,7 +160,6 @@ class Api:
181
160
elif isinstance(chunk, ImagePreview):
182
161
yield self._format_json("preview", chunk.to_string())
183
162
elif isinstance(chunk, ImageResponse):
184
# Обробка ImageResponse
185
163
images = asyncio.run(self._copy_images(chunk.get_list(), chunk.options.get("cookies")))
186
164
yield self._format_json("content", str(ImageResponse(images, chunk.alt)))
187
165
elif not isinstance(chunk, FinishReason):
@@ -190,8 +168,8 @@ class Api:
190
168
logging.exception(e)
191
169
yield self._format_json('error', get_error_message(e))
192
170
193
# Додайте цей метод до класу Api
194
171
async def _copy_images(self, images: list[str], cookies: Optional[Cookies] = None):
172
ensure_images_dir()
195
173
async with ClientSession(
196
174
connector=get_connector(None, os.environ.get("G4F_PROXY")),
197
175
cookies=cookies
@@ -212,16 +190,6 @@ class Api:
212
190
return await asyncio.gather(*[copy_image(image) for image in images])
213
191
214
192
def _format_json(self, response_type: str, content):
215
"""
216
Formats and returns a JSON response.
217
218
Args:
219
response_type (str): The type of the response.
220
content: The content to be included in the response.
221
222
Returns:
223
str: A JSON formatted string.
224
"""
225
193
return {
226
194
'type': response_type,
227
195
response_type: content
@@ -229,15 +197,6 @@ class Api:
229
197
230
198
231
199
def get_error_message(exception: Exception) -> str:
232
"""
233
Generates a formatted error message from an exception.
234
235
Args:
236
exception (Exception): The exception to format.
237
238
Returns:
239
str: A formatted error message string.
240
"""
241
200
message = f"{type(exception).__name__}: {exception}"
242
201
provider = get_last_provider()
243
202
if provider is None: