File size: 2,234 Bytes
d243e97
 
 
 
 
 
 
 
1cf03f7
d243e97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6836dc7
d243e97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bae5645
d243e97
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import Replicate from "replicate"

import { sleep } from "@/lib/sleep"

const replicateToken = `${process.env.AUTH_REPLICATE_API_TOKEN || ""}`
const replicateModel = `${process.env.INTERPOLATION_API_REPLICATE_MODEL || ""}`
const replicateModelVersion = `${process.env.INTERPOLATION_API_REPLICATE_MODEL_VERSION || ""}`

export async function interpolateReplicate(input: string): Promise<string> {
  if (!replicateToken) {
    throw new Error(`you need to configure your AUTH_REPLICATE_API_TOKEN in order to use interpolation`)
  }
  if (!replicateModel) {
    throw new Error(`you need to configure your INTERPOLATION_API_REPLICATE_MODEL in order to use interpolation`)
  }

  if (!replicateModelVersion) {
    throw new Error(`you need to configure your INTERPOLATION_API_REPLICATE_MODEL_VERSION in order to use interpolation`)
  }
  const replicate = new Replicate({ auth: replicateToken })

  const prediction = await replicate.predictions.create({
    version: replicateModelVersion,
    input: {
      mp4: input,
      framerate_multiplier: 4,
      keep_original_duration: true,
    }
  })

  let res: Response
  let pollingCount = 0
  do {
    // This is normally a fast model, so let's check every 4 seconds
    await sleep(4000)

    res = await fetch(`https://api.replicate.com/v1/predictions/${prediction.id}`, {
      method: "GET",
      headers: {
        Authorization: `Token ${replicateToken}`,
      },
      cache: 'no-store',
    })

    // console.log("res:", res)

    /*
    try {
      const text = await res.text()
      console.log("res.text:", text)
    } catch (err) {
      console.error("res.text() error:", err)
    }
    */

    if (res.status === 200) {
      try {
        const response = (await res.json()) as any
        const error = `${response?.error || ""}`
        if (error) {
          throw new Error(error)
        }
        if (response.status === "succeeded") {
          return response.output.pop()
        }
      } catch (err) {
        console.error("res.json() error:", err)
      }
    }

    pollingCount++

    // To prevent indefinite polling, we can stop after a certain number
    if (pollingCount >= 20) {
      throw new Error('Request time out.')
    }
  } while (true)
}