Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

hey I want to make a worker cloudlfare api which generates videos but it got a pretty…

  1. User

    hey I want to make a worker cloudlfare api which generates videos but it got a pretty tough work and I donot want to use a any modules for it it work like it will make a request to https://bytedance-animatediff-lightning.hf.space/queue/join?__theme=dark wit hparams { “data”: [ prompt, “ToonYou”, “”, 4 ], “event_data”: null, “fn_index”: 1, “trigger_id”: 10, “session_hash”: sessionHash } where the prompt is get from user and sessionHash

    function generateRandomSessionHash() { const chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’; let hash = ‘’; for (let i = 0; i < 12; i++) { hash += chars[Math.floor(Math.random() * chars.length)]; } return hash; } 2. it will save the sessionHash temp 3. after that it is gonna make a request https://bytedance-animatediff-lightning.hf.space/queue/data?session_hash=sesionHash now the main part comes the thing is when it is gonna request to https://bytedance-animatediff-lightning.hf.space/queue/data?session_hash= it is streaming and gives the data in streaming format here is the streaming data it shows like data: json… example data: {“msg”: “estimation”, “event_id”: “a2d574d0fb6a4a8ca5e34a4591b88ad1”, “rank”: 0, “queue_size”: 1, “rank_eta”: 6.608385463103061}

    data: {“msg”: “process_starts”, “event_id”: “a2d574d0fb6a4a8ca5e34a4591b88ad1”, “eta”: 6.608385463103061}

    data: {“msg”: “progress”, “event_id”: “a2d574d0fb6a4a8ca5e34a4591b88ad1”, “progress_data”: [{“index”: 0, “length”: 4, “unit”: “steps”, “progress”: null, “desc”: null}]} … data: {“msg”: “progress”, “event_id”: “a2d574d0fb6a4a8ca5e34a4591b88ad1”, “progress_data”: [{“index”: 4, “length”: 4, “unit”: “steps”, “progress”: null, “desc”: null}]} and the resulted response is like data: {"msg": "process_completed", "event_id": "a2d574d0fb6a4a8ca5e34a4591b88ad1", "output": {"data": [{"video": {"path": "/tmp/gradio/bf4024bd4030560f0a8779e1843cfc625b8eb9bc/d2268bc20c234fd3a2116d41cc6050f5.mp4", "url": "https://bytedance-animatediff-lightning.hf.space/file=/tmp/gradio/bf4024bd4030560f0a8779e1843cfc625b8eb9bc/d2268bc20c234fd3a2116d41cc6050f5.mp4", "size": null, "orig_name": "d2268bc20c234fd3a2116d41cc6050f5.mp4", "mime_type": null, "is_stream": false}, "subtitles": null}], "is_generating": false, "duration": 3.350559949874878, "average_duration": 6.341377166072176}, "success": true} and you need to give output.data[0].video.url when the success: true

  2. Assistant

    To achieve the workflow you described using Cloudflare Workers without external modules, you'll need to write a script that handles HTTP requests, performs asynchronous fetch operations to interact with the specified endpoints, and processes streamed JSON responses. Given the constraints and aiming for simplicity, here's a basic approach to structuring your Cloudflare Worker.

    Remember, this script will be simplified to focus on the main tasks: generating a session hash, sending a request with the user's prompt, handling streamed responses, and eventually retrieving the video URL once processing is complete.

    addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest(request) {
      // Parse the incoming request to get the prompt
      const {prompt} = await request.json();
    
      // Generate a session hash
      const sessionHash = generateRandomSessionHash();
    
      // Send the initial request to start the process
      const startResponse = await fetch("https://bytedance-animatediff-lightning.hf.space/queue/join?__theme=dark", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({
          "data": [prompt, "ToonYou", "", 4],
          "event_data": null,
          "fn_index": 1,
          "trigger_id": 10,
          "session_hash": sessionHash
        })
      });
    
      if (!startResponse.ok){
        return new Response("Failed to start the process", {status: 500});
      }
    
      // Now let's poll the second URL for updates
      let videoUrl = await pollForCompletion(sessionHash);
    
      if (videoUrl) {
        // Return the video URL in a response
        return new Response(JSON.stringify({videoUrl}), {status: 200, headers: {"Content-Type": "application/json"}});
      } else {
        return new Response("Error or timeout occurred.", {status: 500});
      }
    }
    
    // Polling function to wait for completion and get the video URL
    async function pollForCompletion(sessionHash) {
      const endpoint = `https://bytedance-animatediff-lightning.hf.space/queue/data?session_hash=${sessionHash}`;
      
      // Note: This is a simplified polling approach. In real use, consider adding proper error handling and possibly incrementing delays between retries.
      for (let i = 0; i < 30; i++) {
        await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second before the next request
        const response = await fetch(endpoint);
        const text = await response.text();
    
        if (text.includes('"msg": "process_completed"')) {
          const successMatch = text.match(/"success": true/);
          if (successMatch) {
              const urlMatch = text.match(/"url": "(https?:\/\/[^"]+)"/);
              return urlMatch ? urlMatch[1] : null;
          }
        }
      }
      // Timeout or error handling goes here
      return null;
    }
    
    // Generate a random session hash
    function generateRandomSessionHash() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let hash = '';
      for (let i = 0; i < 12; i++) {
        hash += chars[Math.floor(Math.random() * chars.length)];
      }
      return hash;
    }
    

    Important Considerations:

    1. Polling Interval and Mechanism: The polling mechanism used here is very basic. Depending on the expected wait time and processing time on the server side, you might need a more sophisticated approach, such as implementing exponential backoff.

    2. Error Handling: This script includes basic error checks but doesn't cover all potential failure points robustly. Ensure to handle network errors, unexpected response formats, and errors from the server adequately in production code.

    3. Security: Sending and receiving data over the network can expose sensitive information. Ensure all data handled is secure, and consider the security implications of the data you're processing.

    4. Server Load: Constantly polling an endpoint could potentially create unnecessary load on the server. Ensure that your approach adheres to the server's usage policies and consider any limitations or quotas that apply.

    Remember, this is a simplified example to give you a starting point. You'll likely need to adjust and expand upon this code based on the specific requirements and constraints of your project and the external services you're interacting with.