NexraDalleMini.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from __future__ import annotations
  2. from aiohttp import ClientSession
  3. import json
  4. from ...typing import AsyncResult, Messages
  5. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  6. from ...image import ImageResponse
  7. class NexraDalleMini(AsyncGeneratorProvider, ProviderModelMixin):
  8. label = "Nexra DALL-E Mini"
  9. url = "https://nexra.aryahcr.cc/documentation/dall-e/en"
  10. api_endpoint = "https://nexra.aryahcr.cc/api/image/complements"
  11. working = True
  12. default_model = 'dalle-mini'
  13. models = [default_model]
  14. @classmethod
  15. def get_model(cls, model: str) -> str:
  16. return cls.default_model
  17. @classmethod
  18. async def create_async_generator(
  19. cls,
  20. model: str,
  21. messages: Messages,
  22. proxy: str = None,
  23. response: str = "url", # base64 or url
  24. **kwargs
  25. ) -> AsyncResult:
  26. # Retrieve the correct model to use
  27. model = cls.get_model(model)
  28. # Format the prompt from the messages
  29. prompt = messages[0]['content']
  30. headers = {
  31. "Content-Type": "application/json"
  32. }
  33. payload = {
  34. "prompt": prompt,
  35. "model": model,
  36. "response": response
  37. }
  38. async with ClientSession(headers=headers) as session:
  39. async with session.post(cls.api_endpoint, json=payload, proxy=proxy) as response:
  40. response.raise_for_status()
  41. text_data = await response.text()
  42. try:
  43. # Parse the JSON response
  44. json_start = text_data.find('{')
  45. json_data = text_data[json_start:]
  46. data = json.loads(json_data)
  47. # Check if the response contains images
  48. if 'images' in data and len(data['images']) > 0:
  49. image_url = data['images'][0]
  50. yield ImageResponse(image_url, prompt)
  51. else:
  52. yield ImageResponse("No images found in the response.", prompt)
  53. except json.JSONDecodeError:
  54. yield ImageResponse("Failed to parse JSON. Response might not be in JSON format.", prompt)