ReplicateHome.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. from __future__ import annotations
  2. import json
  3. import asyncio
  4. from aiohttp import ClientSession, ContentTypeError
  5. from ..typing import AsyncResult, Messages
  6. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  7. from ..requests.aiohttp import get_connector
  8. from ..requests.raise_for_status import raise_for_status
  9. from .helper import format_prompt
  10. from ..image import ImageResponse
  11. class ReplicateHome(AsyncGeneratorProvider, ProviderModelMixin):
  12. url = "https://replicate.com"
  13. api_endpoint = "https://homepage.replicate.com/api/prediction"
  14. working = True
  15. supports_stream = True
  16. supports_system_message = True
  17. supports_message_history = True
  18. default_model = 'google-deepmind/gemma-2b-it'
  19. default_image_model = 'stability-ai/stable-diffusion-3'
  20. image_models = [
  21. 'stability-ai/stable-diffusion-3',
  22. 'bytedance/sdxl-lightning-4step',
  23. 'playgroundai/playground-v2.5-1024px-aesthetic',
  24. ]
  25. text_models = [
  26. 'google-deepmind/gemma-2b-it',
  27. ]
  28. models = text_models + image_models
  29. model_aliases = {
  30. # image_models
  31. "sd-3": "stability-ai/stable-diffusion-3",
  32. "sdxl": "bytedance/sdxl-lightning-4step",
  33. "playground-v2.5": "playgroundai/playground-v2.5-1024px-aesthetic",
  34. # text_models
  35. "gemma-2b": "google-deepmind/gemma-2b-it",
  36. }
  37. model_versions = {
  38. # image_models
  39. 'stability-ai/stable-diffusion-3': "527d2a6296facb8e47ba1eaf17f142c240c19a30894f437feee9b91cc29d8e4f",
  40. 'bytedance/sdxl-lightning-4step': "5f24084160c9089501c1b3545d9be3c27883ae2239b6f412990e82d4a6210f8f",
  41. 'playgroundai/playground-v2.5-1024px-aesthetic': "a45f82a1382bed5c7aeb861dac7c7d191b0fdf74d8d57c4a0e6ed7d4d0bf7d24",
  42. # text_models
  43. "google-deepmind/gemma-2b-it": "dff94eaf770e1fc211e425a50b51baa8e4cac6c39ef074681f9e39d778773626",
  44. }
  45. @classmethod
  46. async def create_async_generator(
  47. cls,
  48. model: str,
  49. messages: Messages,
  50. prompt: str = None,
  51. proxy: str = None,
  52. **kwargs
  53. ) -> AsyncResult:
  54. model = cls.get_model(model)
  55. headers = {
  56. "accept": "*/*",
  57. "accept-language": "en-US,en;q=0.9",
  58. "content-type": "application/json",
  59. "origin": "https://replicate.com",
  60. "referer": "https://replicate.com/",
  61. "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
  62. }
  63. async with ClientSession(headers=headers, connector=get_connector(proxy=proxy)) as session:
  64. if prompt is None:
  65. if model in cls.image_models:
  66. prompt = messages[-1]['content']
  67. else:
  68. prompt = format_prompt(messages)
  69. data = {
  70. "model": model,
  71. "version": cls.model_versions[model],
  72. "input": {"prompt": prompt},
  73. }
  74. async with session.post(cls.api_endpoint, json=data) as response:
  75. await raise_for_status(response)
  76. result = await response.json()
  77. prediction_id = result['id']
  78. poll_url = f"https://homepage.replicate.com/api/poll?id={prediction_id}"
  79. max_attempts = 30
  80. delay = 5
  81. for _ in range(max_attempts):
  82. async with session.get(poll_url) as response:
  83. await raise_for_status(response)
  84. try:
  85. result = await response.json()
  86. except ContentTypeError:
  87. text = await response.text()
  88. try:
  89. result = json.loads(text)
  90. except json.JSONDecodeError:
  91. raise ValueError(f"Unexpected response format: {text}")
  92. if result['status'] == 'succeeded':
  93. if model in cls.image_models:
  94. image_url = result['output'][0]
  95. yield ImageResponse(image_url, prompt)
  96. return
  97. else:
  98. for chunk in result['output']:
  99. yield chunk
  100. break
  101. elif result['status'] == 'failed':
  102. raise Exception(f"Prediction failed: {result.get('error')}")
  103. await asyncio.sleep(delay)
  104. if result['status'] != 'succeeded':
  105. raise Exception("Prediction timed out")