import asyncio import aiohttp import replicate import os from aiohttp import web from…
- User
import asyncio import aiohttp import replicate import os from aiohttp import web from dotenv import load_dotenv
Load environment variables from .env file
load_dotenv()
Get the API token from environment variables
API_TOKEN = os.getenv("REPLICATE_API_TOKEN") if not API_TOKEN: raise ValueError("API token not found. Please set it in the .env file.")
Initialize your Replicate client
replicate_client = replicate.Client(api_token=API_TOKEN)
Define the callback URL
callback_url = "https://my.app/webhooks/replicate"
Create a basic web server using aiohttp
routes = web.RouteTableDef()
@routes.post('/webhooks/replicate') async def callback_replicate(request): prediction = await request.json() print(prediction) # Handle the prediction result here return web.Response(text="OK")
async def run_server(): app = web.Application() app.add_routes(routes) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, port=8080) await site.start() print("Server started at http://localhost:8080") while True: await asyncio.sleep(3600) # Run server indefinitely
async def create_prediction(prompt): input_data = { "prompt": prompt, "lora_scale": 0.8, "aspect_ratio": "16:9" }
# Create the prediction prediction = replicate_client.predictions.create( version="f5e694fa1a88ccc1d2d3f660f4936d762a05f04689a2d1d634893aeb6d6da955", input=input_data, webhook=callback_url, webhook_events_filter=["completed"] ) print(f"Prediction ID: {prediction.id}") # Wait for the prediction to complete for _ in range(2): # Poll a maximum of 2 times await asyncio.sleep(5) # Wait before polling prediction = replicate_client.predictions.get(prediction.id) # Get the updated prediction status if prediction.status == "completed": print(f"Prediction completed with result: {prediction.output}") break else: print("Prediction did not complete in expected time.")async def main(): # Start the server and create the prediction concurrently await asyncio.gather(run_server(), create_prediction("Tokyo street in the style of STL with neon lights at night"))
if name == "main": asyncio.run(main()) What is needed
- Assistant