novelai-python 0.7.2__tar.gz → 0.7.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. {novelai_python-0.7.2 → novelai_python-0.7.3}/PKG-INFO +1 -1
  2. {novelai_python-0.7.2 → novelai_python-0.7.3}/pyproject.toml +1 -1
  3. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_exceptions.py +8 -0
  4. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/augment_image/__init__.py +75 -64
  5. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate/__init__.py +1 -1
  6. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate_image/__init__.py +102 -74
  7. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate_image/suggest_tags.py +10 -23
  8. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate_stream.py +1 -1
  9. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate_voice/__init__.py +31 -48
  10. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate_voice/_enum.py +14 -15
  11. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/upscale.py +66 -62
  12. novelai_python-0.7.3/src/novelai_python/sdk/schema.py +91 -0
  13. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/user/information.py +8 -23
  14. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/user/login.py +8 -23
  15. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/user/subscription.py +7 -23
  16. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tokenizer/__init__.py +9 -1
  17. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_generate_voice.py +11 -6
  18. novelai_python-0.7.2/src/novelai_python/sdk/schema.py +0 -36
  19. {novelai_python-0.7.2 → novelai_python-0.7.3}/LICENSE +0 -0
  20. {novelai_python-0.7.2 → novelai_python-0.7.3}/NOTICE.MD +0 -0
  21. {novelai_python-0.7.2 → novelai_python-0.7.3}/README.md +0 -0
  22. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/__init__.py +0 -0
  23. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_enum.py +0 -0
  24. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/__init__.py +0 -0
  25. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/ai/__init__.py +0 -0
  26. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/ai/generate.py +0 -0
  27. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/ai/generate_image.py +0 -0
  28. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/ai/generate_stream.py +0 -0
  29. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/ai/generate_voice.py +0 -0
  30. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/ai/upscale.py +0 -0
  31. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/schema.py +0 -0
  32. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/user/__init__.py +0 -0
  33. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/user/information.py +0 -0
  34. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/user/login.py +0 -0
  35. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/_response/user/subscription.py +0 -0
  36. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/credential/ApiToken.py +0 -0
  37. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/credential/JwtToken.py +0 -0
  38. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/credential/UserAuth.py +0 -0
  39. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/credential/__init__.py +0 -0
  40. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/credential/_base.py +0 -0
  41. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/__init__.py +0 -0
  42. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/LICENSE +0 -0
  43. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/__init__.py +0 -0
  44. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/_const.py +0 -0
  45. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/_cost.py +0 -0
  46. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/_enum.py +0 -0
  47. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/augment_image/_enum.py +0 -0
  48. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate/_const.py +0 -0
  49. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate/_enum.py +0 -0
  50. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate/_schema.py +0 -0
  51. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate/themes.json +0 -0
  52. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/ai/generate_image/schema.py +0 -0
  53. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/sdk/user/__init__.py +0 -0
  54. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/server.py +0 -0
  55. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tokenizer/clip_simple_tokenizer.py +0 -0
  56. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tokenizer/nerdstash_v1.model +0 -0
  57. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tokenizer/nerdstash_v2.model +0 -0
  58. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tokenizer/novelai.model +0 -0
  59. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tokenizer/novelai_v2.model +0 -0
  60. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/__init__.py +0 -0
  61. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/image_metadata/__init__.py +0 -0
  62. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/image_metadata/bch_utils.py +0 -0
  63. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/image_metadata/lsb_extractor.py +0 -0
  64. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/image_metadata/lsb_injector.py +0 -0
  65. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/paint_mask/__init__.py +0 -0
  66. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/random_prompt/__init__.py +0 -0
  67. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/random_prompt/generate_scene_composition.py +0 -0
  68. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/random_prompt/generate_scene_tags.py +0 -0
  69. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/tool/random_prompt/generate_tags.py +0 -0
  70. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/utils/__init__.py +0 -0
  71. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/utils/encode.py +0 -0
  72. {novelai_python-0.7.2 → novelai_python-0.7.3}/src/novelai_python/utils/useful.py +0 -0
  73. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/__init__.py +0 -0
  74. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_random_prompt.py +0 -0
  75. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_server.py +0 -0
  76. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_server_run.py +0 -0
  77. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_tokenizer.py +0 -0
  78. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_upscale.py +0 -0
  79. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_user_information.py +0 -0
  80. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_user_login.py +0 -0
  81. {novelai_python-0.7.2 → novelai_python-0.7.3}/tests/test_user_subscription.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: novelai-python
3
- Version: 0.7.2
3
+ Version: 0.7.3
4
4
  Summary: NovelAI Python Binding With Pydantic
5
5
  Author-Email: sudoskys <coldlando@hotmail.com>
6
6
  License: Apache License 2.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "novelai-python"
3
- version = "0.7.2"
3
+ version = "0.7.3"
4
4
  description = "NovelAI Python Binding With Pydantic"
5
5
  authors = [
6
6
  { name = "sudoskys", email = "coldlando@hotmail.com" },
@@ -74,6 +74,14 @@ class ConcurrentGenerationError(APIError):
74
74
  pass
75
75
 
76
76
 
77
+ class DataSerializationError(APIError):
78
+ """
79
+ DataSerializationError is raised when the API data is not serializable.
80
+ """
81
+
82
+ pass
83
+
84
+
77
85
  class AuthError(APIError):
78
86
  """
79
87
  AuthError is raised when the API returns an error.
@@ -11,7 +11,7 @@ from copy import deepcopy
11
11
  from io import BytesIO
12
12
  from typing import Optional, Union, IO, Any
13
13
  from urllib.parse import urlparse
14
- from zipfile import ZipFile
14
+ from zipfile import ZipFile, BadZipFile
15
15
 
16
16
  import curl_cffi
17
17
  import httpx
@@ -25,13 +25,16 @@ from novelai_python.sdk.ai._cost import CostCalculator
25
25
  from novelai_python.sdk.ai._enum import Model
26
26
  from ._enum import ReqType, Moods
27
27
  from ...schema import ApiBaseModel
28
- from ...._exceptions import APIError, AuthError, ConcurrentGenerationError, SessionHttpError
28
+ from ...._exceptions import APIError, AuthError, ConcurrentGenerationError, SessionHttpError, DataSerializationError
29
29
  from ...._response.ai.generate_image import ImageGenerateResp, RequestParams
30
30
  from ....credential import CredentialBase
31
31
  from ....utils import try_jsonfy
32
32
 
33
33
 
34
34
  class AugmentImageInfer(ApiBaseModel):
35
+ """
36
+ https://docs.novelai.net/image/directortools.html
37
+ """
35
38
  _endpoint: str = PrivateAttr("https://image.novelai.net")
36
39
 
37
40
  @property
@@ -210,96 +213,104 @@ class AugmentImageInfer(ApiBaseModel):
210
213
  :param session: session
211
214
  :return:
212
215
  """
213
- # Data Build
216
+ # Prepare request data
214
217
  request_data = self.model_dump(mode="json", exclude_none=True)
215
218
  async with session if isinstance(session, AsyncSession) else await session.get_session() as sess:
216
- # Header
217
219
  sess.headers.update(await self.necessary_headers(request_data))
218
220
  if override_headers:
219
221
  sess.headers.clear()
220
222
  sess.headers.update(override_headers)
223
+
224
+ # Log the request data (sanitize sensitive content)
221
225
  try:
222
226
  _log_data = deepcopy(request_data)
223
- _log_data.update({
224
- "image": "base64 data"
225
- })
226
- logger.debug(f"Request Data: {_log_data}")
227
- del _log_data
227
+ if self.image:
228
+ _log_data["image"] = "base64 data hidden"
229
+ logger.debug(f"Request Data: {json.dumps(_log_data, indent=2)}")
228
230
  except Exception as e:
229
- logger.warning(f"Error when print log data: {e}")
231
+ logger.warning(f"Failed to log request data: {e}")
232
+
233
+ # Perform request and handle response
230
234
  try:
231
- assert hasattr(sess, "post"), "session must have post method."
235
+ self.ensure_session_has_post_method(sess)
232
236
  response = await sess.post(
233
237
  self.base_url,
234
238
  data=json.dumps(request_data).encode("utf-8")
235
239
  )
236
- if response.headers.get('Content-Type') not in ['binary/octet-stream', 'application/x-zip-compressed']:
237
- logger.warning(
238
- f"Error with content type: {response.headers.get('Content-Type')} and code: {response.status_code}"
239
- )
240
- try:
241
- _msg = response.json()
242
- except Exception as e:
243
- logger.warning(e)
244
- if not isinstance(response.content, str) and len(response.content) < 50:
245
- raise APIError(
246
- message=f"Unexpected content type: {response.headers.get('Content-Type')}",
247
- request=request_data,
248
- code=response.status_code,
249
- response=try_jsonfy(response.content)
250
- )
251
- else:
252
- _msg = {"statusCode": response.status_code, "message": response.content}
253
- status_code = _msg.get("statusCode", response.status_code)
254
- message = _msg.get("message", "Unknown error")
240
+ if (
241
+ response.headers.get('Content-Type') not in ['binary/octet-stream',
242
+ 'application/x-zip-compressed']
243
+ or response.status_code >= 400
244
+ ):
245
+ error_message = await self.handle_error_response(response, request_data)
246
+ status_code = error_message.get("statusCode", response.status_code)
247
+ message = error_message.get("message", "Unknown error")
255
248
  if status_code in [400, 401, 402]:
256
249
  # 400 : validation error
257
250
  # 401 : unauthorized
258
251
  # 402 : payment required
259
252
  # 409 : conflict
260
- raise AuthError(message, request=request_data, code=status_code, response=_msg)
261
- if status_code in [409]:
262
- # conflict error
263
- raise APIError(message, request=request_data, code=status_code, response=_msg)
264
- if status_code in [429]:
265
- # concurrent error
253
+ raise AuthError(message, request=request_data, code=status_code, response=error_message)
254
+ elif status_code == 409:
255
+ raise APIError(message, request=request_data, code=status_code, response=error_message)
256
+ elif status_code == 429:
266
257
  raise ConcurrentGenerationError(
267
258
  message=message,
268
259
  request=request_data,
269
260
  code=status_code,
270
- response=_msg
271
- )
272
- raise APIError(message, request=request_data, code=status_code, response=_msg)
273
- zip_file = ZipFile(BytesIO(response.content))
274
- unzip_content = []
275
- with zip_file as zf:
276
- file_list = zf.namelist()
277
- if not file_list:
278
- raise APIError(
279
- message="No file in zip",
280
- request=request_data,
281
- code=response.status_code,
282
- response=try_jsonfy(response.content)
261
+ response=error_message,
283
262
  )
284
- for filename in file_list:
285
- data = zip_file.read(filename)
286
- unzip_content.append((filename, data))
287
- return ImageGenerateResp(
288
- meta=RequestParams(
289
- endpoint=self.base_url,
290
- raw_request=request_data,
291
- ),
292
- files=unzip_content
293
- )
263
+ else:
264
+ raise APIError(message, request=request_data, code=status_code, response=error_message)
265
+
266
+ # Unpack the ZIP response
267
+ try:
268
+ zip_file = ZipFile(BytesIO(response.content))
269
+ unzip_content = []
270
+ with zip_file as zf:
271
+ file_list = zf.namelist()
272
+ if not file_list:
273
+ raise DataSerializationError(
274
+ message="The ZIP response contains no files.",
275
+ request=request_data,
276
+ response=try_jsonfy(response.content),
277
+ code=response.status_code,
278
+ )
279
+ for filename in file_list:
280
+ data = zip_file.read(filename)
281
+ unzip_content.append((filename, data))
282
+ return ImageGenerateResp(
283
+ meta=RequestParams(
284
+ endpoint=self.base_url,
285
+ raw_request=request_data,
286
+ ),
287
+ files=unzip_content,
288
+ )
289
+ except BadZipFile as e:
290
+ # Invalid ZIP file - indicate serialization error
291
+ logger.exception("The response content is not a valid ZIP file.")
292
+ raise DataSerializationError(
293
+ message="Invalid ZIP file received from the API.",
294
+ request=request_data,
295
+ response={},
296
+ code=response.status_code,
297
+ ) from e
298
+ except Exception as e:
299
+ logger.exception("Unexpected error while unpacking ZIP response.")
300
+ raise DataSerializationError(
301
+ message="An unexpected error occurred while processing ZIP data.",
302
+ request=request_data,
303
+ response={},
304
+ code=response.status_code,
305
+ ) from e
294
306
  except curl_cffi.requests.errors.RequestsError as exc:
295
307
  logger.exception(exc)
296
- raise SessionHttpError(
297
- "An AsyncSession RequestsError occurred, maybe SSL error. Try again later!") from exc
308
+ raise SessionHttpError("A RequestsError occurred (e.g., SSL error). Try again later.")
298
309
  except httpx.HTTPError as exc:
299
310
  logger.exception(exc)
300
- raise SessionHttpError("An HTTPError occurred, maybe SSL error. Try again later!") from exc
311
+ raise SessionHttpError("An HTTP error occurred. Try again later.")
301
312
  except APIError as e:
302
313
  raise e
303
314
  except Exception as e:
304
- logger.opt(exception=e).exception("An Unexpected error occurred")
305
- raise e
315
+ logger.opt(exception=e).exception("Unexpected error occurred during the request.")
316
+ raise Exception("An unexpected error occurred.") from e
@@ -369,7 +369,7 @@ class LLM(ApiBaseModel):
369
369
  logger.debug(f"LLM request data: {json.dumps(request_data)}")
370
370
  # Request
371
371
  try:
372
- assert hasattr(sess, "post"), "session must have post method."
372
+ self.ensure_session_has_post_method(sess)
373
373
  response = await sess.post(
374
374
  self.base_url,
375
375
  json=request_data,
@@ -12,7 +12,7 @@ from enum import Enum
12
12
  from io import BytesIO
13
13
  from typing import Optional, Union, Tuple, List
14
14
  from urllib.parse import urlparse
15
- from zipfile import ZipFile
15
+ from zipfile import ZipFile, BadZipFile
16
16
 
17
17
  import curl_cffi
18
18
  import cv2
@@ -32,7 +32,7 @@ from novelai_python.sdk.ai._enum import Model, Sampler, NoiseSchedule, ControlNe
32
32
  get_model_group, ModelGroups, get_supported_params, get_modifiers, ImageBytesTypeAlias
33
33
  from .schema import Character, V4Prompt, V4NegativePrompt, PositionMap
34
34
  from ...schema import ApiBaseModel
35
- from ...._exceptions import APIError, AuthError, ConcurrentGenerationError, SessionHttpError
35
+ from ...._exceptions import APIError, AuthError, ConcurrentGenerationError, SessionHttpError, DataSerializationError
36
36
  from ...._response.ai.generate_image import ImageGenerateResp, RequestParams
37
37
  from ....credential import CredentialBase
38
38
  from ....utils import try_jsonfy
@@ -403,10 +403,19 @@ class GenerateImageInfer(ApiBaseModel):
403
403
  # Add negative prompt based on ucPreset
404
404
  if self.parameters.ucPreset is not None:
405
405
  uc_preset = self.parameters.ucPreset
406
+
406
407
  # If ucPreset is Enum, get the value
407
408
  if isinstance(self.parameters.ucPreset, Enum):
408
409
  uc_preset = self.parameters.ucPreset.value
409
410
  default_negative_prompt = get_default_uc_preset(self.model, uc_preset)
411
+
412
+ # Lowres means we don't found any negative prompt.
413
+ # If the default negative prompt is lowres, and the user has set a negative prompt,
414
+ # then the default negative prompt is not added.
415
+ if self.parameters.negative_prompt and default_negative_prompt == "lowres":
416
+ default_negative_prompt = ""
417
+
418
+ # Combine the negative prompt preset and the user's negative prompt
410
419
  self.parameters.negative_prompt = ", ".join(
411
420
  filter(None, [default_negative_prompt, self.parameters.negative_prompt])
412
421
  )
@@ -986,113 +995,132 @@ class GenerateImageInfer(ApiBaseModel):
986
995
  retry=retry_if_exception(lambda e: hasattr(e, "code") and str(e.code) == "500"),
987
996
  reraise=True
988
997
  )
989
- async def request(self,
990
- session: Union[AsyncSession, "CredentialBase"],
991
- *,
992
- override_headers: Optional[dict] = None,
993
- ) -> ImageGenerateResp:
998
+ async def request(
999
+ self,
1000
+ session: Union[AsyncSession, "CredentialBase"],
1001
+ *,
1002
+ override_headers: Optional[dict] = None,
1003
+ ) -> ImageGenerateResp:
994
1004
  """
995
1005
  **Generate images using NovelAI's diffusion models.**
996
1006
 
997
- According to our Terms of Service, all generation requests must be initiated by a human action. Automating text or image generation to create excessive load on our systems is not allowed.
998
-
999
- :param override_headers: the headers to override
1000
- :param session: session
1001
- :return:
1007
+ According to our Terms of Service, all generation requests must be initiated by a human action. Automating text
1008
+ or image generation to create excessive load on our systems is not allowed.
1009
+
1010
+ :param override_headers: Headers to override the default headers.
1011
+ :param session: Async session object or credential-based session.
1012
+ :return: ImageGenerateResp containing the response data and metadata.
1013
+ :raises AuthError: If the request is unauthorized.
1014
+ :raises APIError: If the API returns an error.
1015
+ :raises ConcurrentGenerationError: If the request is rate-limited.
1016
+ :raises SessionHttpError: If an HTTP error occurs.
1017
+ :raises DataSerializationError: If an error occurs while processing the response data.
1002
1018
  """
1003
- # Data Build
1019
+ # Prepare request data
1004
1020
  request_data = self.model_dump(mode="json", exclude_none=True)
1005
1021
  async with session if isinstance(session, AsyncSession) else await session.get_session() as sess:
1006
- # Header
1007
1022
  sess.headers.update(await self.necessary_headers(request_data))
1008
1023
  if override_headers:
1009
1024
  sess.headers.clear()
1010
1025
  sess.headers.update(override_headers)
1026
+
1027
+ # Log the request data (sanitize sensitive content)
1011
1028
  try:
1012
1029
  _log_data = deepcopy(request_data)
1013
1030
  if self.parameters.image:
1014
- _log_data["parameters"]["image"] = "base64 data"
1031
+ _log_data["parameters"]["image"] = "base64 data hidden"
1015
1032
  if self.parameters.mask:
1016
- _log_data["parameters"]["mask"] = "base64 data"
1033
+ _log_data["parameters"]["mask"] = "base64 data hidden"
1017
1034
  if self.parameters.reference_image_multiple:
1018
- _log_data["parameters"]["reference_image_multiple"] = ["base64 data"] * len(
1019
- self.parameters.reference_image_multiple)
1035
+ _log_data["parameters"]["reference_image_multiple"] = ["base64 data hidden"] * len(
1036
+ self.parameters.reference_image_multiple
1037
+ )
1020
1038
  logger.debug(f"Request Data: {json.dumps(_log_data, indent=2)}")
1021
- del _log_data
1022
1039
  except Exception as e:
1023
- logger.warning(f"Error when print log data: {e}")
1040
+ logger.warning(f"Failed to log request data: {e}")
1041
+
1042
+ # Perform request and handle response
1024
1043
  try:
1025
- assert hasattr(sess, "post"), "session must have post method."
1044
+ self.ensure_session_has_post_method(sess)
1026
1045
  response = await sess.post(
1027
1046
  self.base_url,
1028
- data=json.dumps(request_data).encode("utf-8")
1047
+ data=json.dumps(request_data).encode("utf-8"),
1029
1048
  )
1030
- if response.headers.get('Content-Type') not in ['binary/octet-stream', 'application/x-zip-compressed']:
1031
- logger.warning(
1032
- f"Error with content type: {response.headers.get('Content-Type')} and code: {response.status_code}"
1033
- )
1034
- try:
1035
- _msg = response.json()
1036
- except Exception as e:
1037
- logger.warning(e)
1038
- if not isinstance(response.content, str) and len(response.content) < 50:
1039
- raise APIError(
1040
- message=f"Unexpected content type: {response.headers.get('Content-Type')}",
1041
- request=request_data,
1042
- code=response.status_code,
1043
- response=try_jsonfy(response.content)
1044
- )
1045
- else:
1046
- _msg = {"statusCode": response.status_code, "message": response.content}
1047
- status_code = _msg.get("statusCode", response.status_code)
1048
- message = _msg.get("message", "Unknown error")
1049
+ # Validate response content type and status code
1050
+ if (
1051
+ response.headers.get("Content-Type")
1052
+ not in ["binary/octet-stream", "application/x-zip-compressed"]
1053
+ or response.status_code >= 400
1054
+ ):
1055
+ error_message = await self.handle_error_response(response, request_data)
1056
+ status_code = error_message.get("statusCode", response.status_code)
1057
+ message = error_message.get("message", "Unknown error")
1049
1058
  if status_code in [400, 401, 402]:
1050
1059
  # 400 : validation error
1051
1060
  # 401 : unauthorized
1052
1061
  # 402 : payment required
1053
1062
  # 409 : conflict
1054
- raise AuthError(message, request=request_data, code=status_code, response=_msg)
1055
- if status_code in [409]:
1056
- # conflict error
1057
- raise APIError(message, request=request_data, code=status_code, response=_msg)
1058
- if status_code in [429]:
1059
- # concurrent error
1063
+ raise AuthError(message, request=request_data, code=status_code, response=error_message)
1064
+ elif status_code == 409:
1065
+ raise APIError(message, request=request_data, code=status_code, response=error_message)
1066
+ elif status_code == 429:
1060
1067
  raise ConcurrentGenerationError(
1061
1068
  message=message,
1062
1069
  request=request_data,
1063
1070
  code=status_code,
1064
- response=_msg
1071
+ response=error_message,
1065
1072
  )
1066
- raise APIError(message, request=request_data, code=status_code, response=_msg)
1067
- zip_file = ZipFile(BytesIO(response.content))
1068
- unzip_content = []
1069
- with zip_file as zf:
1070
- file_list = zf.namelist()
1071
- if not file_list:
1072
- raise APIError(
1073
- message="No file in zip",
1074
- request=request_data,
1075
- code=response.status_code,
1076
- response=try_jsonfy(response.content)
1077
- )
1078
- for filename in file_list:
1079
- data = zip_file.read(filename)
1080
- unzip_content.append((filename, data))
1081
- return ImageGenerateResp(
1082
- meta=RequestParams(
1083
- endpoint=self.base_url,
1084
- raw_request=request_data,
1085
- ),
1086
- files=unzip_content
1087
- )
1073
+ else:
1074
+ raise APIError(message, request=request_data, code=status_code, response=error_message)
1075
+
1076
+ # Unpack the ZIP response
1077
+ try:
1078
+ zip_file = ZipFile(BytesIO(response.content))
1079
+ unzip_content = []
1080
+ with zip_file as zf:
1081
+ file_list = zf.namelist()
1082
+ if not file_list:
1083
+ raise DataSerializationError(
1084
+ message="The ZIP response contains no files.",
1085
+ request=request_data,
1086
+ response=try_jsonfy(response.content),
1087
+ code=response.status_code,
1088
+ )
1089
+ for filename in file_list:
1090
+ data = zip_file.read(filename)
1091
+ unzip_content.append((filename, data))
1092
+ return ImageGenerateResp(
1093
+ meta=RequestParams(
1094
+ endpoint=self.base_url,
1095
+ raw_request=request_data,
1096
+ ),
1097
+ files=unzip_content,
1098
+ )
1099
+ except BadZipFile as e:
1100
+ # Invalid ZIP file - indicate serialization error
1101
+ logger.exception("The response content is not a valid ZIP file.")
1102
+ raise DataSerializationError(
1103
+ message="Invalid ZIP file received from the API.",
1104
+ request=request_data,
1105
+ response={},
1106
+ code=response.status_code,
1107
+ ) from e
1108
+ except Exception as e:
1109
+ logger.exception("Unexpected error while unpacking ZIP response.")
1110
+ raise DataSerializationError(
1111
+ message="An unexpected error occurred while processing ZIP data.",
1112
+ request=request_data,
1113
+ response={},
1114
+ code=response.status_code,
1115
+ ) from e
1088
1116
  except curl_cffi.requests.errors.RequestsError as exc:
1089
1117
  logger.exception(exc)
1090
- raise SessionHttpError("An AsyncSession RequestsError occurred, maybe SSL error. Try again later!")
1118
+ raise SessionHttpError("A RequestsError occurred (e.g., SSL error). Try again later.")
1091
1119
  except httpx.HTTPError as exc:
1092
1120
  logger.exception(exc)
1093
- raise SessionHttpError("An HTTPError occurred, maybe SSL error. Try again later!")
1121
+ raise SessionHttpError("An HTTP error occurred. Try again later.")
1094
1122
  except APIError as e:
1095
1123
  raise e
1096
1124
  except Exception as e:
1097
- logger.opt(exception=e).exception("An Unexpected error occurred")
1098
- raise e
1125
+ logger.opt(exception=e).exception("Unexpected error occurred during the request.")
1126
+ raise Exception("An unexpected error occurred.") from e
@@ -77,41 +77,28 @@ class SuggestTags(ApiBaseModel):
77
77
  if override_headers:
78
78
  session.headers.clear()
79
79
  session.headers.update(override_headers)
80
- logger.debug("SuggestTags")
81
80
  try:
82
81
  assert hasattr(session, "get"), "session must have get method."
83
82
  response = await session.get(
84
83
  url=self.base_url + "?" + "&".join([f"{k}={v}" for k, v in request_data.items()])
85
84
  )
86
- if "application/json" not in response.headers.get('Content-Type') or response.status_code != 200:
87
- logger.warning(
88
- f"Error with content type: {response.headers.get('Content-Type')} and code: {response.status_code}"
89
- )
90
- try:
91
- _msg = response.json()
92
- except Exception as e:
93
- logger.warning(e)
94
- if not isinstance(response.content, str) and len(response.content) < 50:
95
- raise APIError(
96
- message=f"Unexpected content type: {response.headers.get('Content-Type')}",
97
- request=request_data,
98
- code=response.status_code,
99
- response=try_jsonfy(response.content)
100
- )
101
- else:
102
- _msg = {"statusCode": response.status_code, "message": response.content}
103
- status_code = _msg.get("statusCode", response.status_code)
104
- message = _msg.get("message", "Unknown error")
85
+ if (
86
+ "application/json" not in response.headers.get('Content-Type')
87
+ or response.status_code != 200
88
+ ):
89
+ error_message = await self.handle_error_response(response=response, request_data=request_data)
90
+ status_code = error_message.get("statusCode", response.status_code)
91
+ message = error_message.get("message", "Unknown error")
105
92
  if status_code in [400, 401, 402]:
106
93
  # 400 : validation error
107
94
  # 401 : unauthorized
108
95
  # 402 : payment required
109
96
  # 409 : conflict
110
- raise AuthError(message, request=request_data, code=status_code, response=_msg)
97
+ raise AuthError(message, request=request_data, code=status_code, response=error_message)
111
98
  if status_code in [500]:
112
99
  # An unknown error occured.
113
- raise APIError(message, request=request_data, code=status_code, response=_msg)
114
- raise APIError(message, request=request_data, code=status_code, response=_msg)
100
+ raise APIError(message, request=request_data, code=status_code, response=error_message)
101
+ raise APIError(message, request=request_data, code=status_code, response=error_message)
115
102
  return SuggestTagsResp.model_validate(response.json())
116
103
  except curl_cffi.requests.errors.RequestsError as exc:
117
104
  logger.exception(exc)
@@ -95,7 +95,7 @@ class LLMStream(LLM):
95
95
  logger.debug(f"StreamLLM request data: {request_data}")
96
96
  # Request
97
97
  try:
98
- assert hasattr(sess, "post"), "session must have post method."
98
+ self.ensure_session_has_post_method(sess)
99
99
  response = await sess.post(
100
100
  self.base_url,
101
101
  json=request_data,