Skip to content

Commit

Permalink
now working, still need to add server actions
Browse files Browse the repository at this point in the history
  • Loading branch information
Nutlope committed Jun 1, 2023
1 parent e89a2d8 commit 950d121
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 31 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,7 @@ This repo is MIT licensed.
## Todos

- Update OG image design + include "roomgpt.io"
- Add Server Actions
- Use Replicate's nodejs library
- Migrate to use edge functions
- Add loading states with suspense and useOptimistic server action hook
18 changes: 2 additions & 16 deletions app/generate/route.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,8 @@
import { Ratelimit } from "@upstash/ratelimit";
import type { NextApiRequest, NextApiResponse } from "next";
import requestIp from "request-ip";
import redis from "../../utils/redis";
import { NextResponse } from "next/server";
import { headers } from "next/headers";

type Data = string;
interface ExtendedNextApiRequest extends NextApiRequest {
body: {
imageUrl: string;
theme: string;
room: string;
};
}

// Create a new ratelimiter, that allows 5 requests per 24 hours
const ratelimit = redis
? new Ratelimit({
Expand All @@ -27,11 +16,9 @@ export async function POST(request: Request) {
// Rate Limiter Code
if (ratelimit) {
const headersList = headers();
const referer = headersList.get("RemoteAddr");
const ipIdentifier = headersList.get("x-real-ip");

const result = await ratelimit.limit(referer!);
// res.setHeader("X-RateLimit-Limit", result.limit);
// res.setHeader("X-RateLimit-Remaining", result.remaining);
const result = await ratelimit.limit(ipIdentifier ?? "");

if (!result.success) {
return new Response(
Expand All @@ -48,7 +35,6 @@ export async function POST(request: Request) {
}

const { imageUrl, theme, room } = await request.json();
// const { imageUrl, theme, room } = req.body;

// POST request to Replicate to start the image restoration generation process
let startResponse = await fetch("https://api.replicate.com/v1/predictions", {
Expand Down
15 changes: 0 additions & 15 deletions app/test/route.ts

This file was deleted.

3 changes: 3 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
serverActions: true,
},
reactStrictMode: true,
images: {
domains: ["upcdn.io", "replicate.delivery"],
Expand Down
96 changes: 96 additions & 0 deletions utils/submitImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { Ratelimit } from "@upstash/ratelimit";
import redis from "../utils/redis";
import { headers } from "next/headers";

// Create a new ratelimiter, that allows 5 requests per 24 hours
const ratelimit = redis
? new Ratelimit({
redis: redis,
limiter: Ratelimit.fixedWindow(5, "1440 m"),
analytics: true,
})
: undefined;

export default async function submitImage({
imageUrl,
theme,
room,
}: {
imageUrl: string;
theme: string;
room: string;
}) {
// Rate Limiter Code
if (ratelimit) {
const headersList = headers();
const ipIdentifier = headersList.get("x-real-ip");

const result = await ratelimit.limit(ipIdentifier ?? "");

if (!result.success) {
return new Response(
"Too many uploads in 1 day. Please try again in a 24 hours.",
{
status: 429,
headers: {
"X-RateLimit-Limit": result.limit,
"X-RateLimit-Remaining": result.remaining,
} as any,
}
);
}
}

// POST request to Replicate to start the image restoration generation process
let startResponse = await fetch("https://api.replicate.com/v1/predictions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Token " + process.env.REPLICATE_API_KEY,
},
body: JSON.stringify({
version:
"854e8727697a057c525cdb45ab037f64ecca770a1769cc52287c2e56472a247b",
input: {
image: imageUrl,
prompt:
room === "Gaming Room"
? "a room for gaming with gaming computers, gaming consoles, and gaming chairs"
: `a ${theme.toLowerCase()} ${room.toLowerCase()}`,
a_prompt:
"best quality, extremely detailed, photo from Pinterest, interior, cinematic photo, ultra-detailed, ultra-realistic, award-winning",
n_prompt:
"longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality",
},
}),
});

let jsonStartResponse = await startResponse.json();

let endpointUrl = jsonStartResponse.urls.get;

// GET request to get the status of the image restoration process & return the result when it's ready
let redesignedImage: string | null = null;
while (!redesignedImage) {
// Loop in 1s intervals until the alt text is ready
console.log("polling for result...");
let finalResponse = await fetch(endpointUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Token " + process.env.REPLICATE_API_KEY,
},
});
let jsonFinalResponse = await finalResponse.json();

if (jsonFinalResponse.status === "succeeded") {
redesignedImage = jsonFinalResponse.output;
} else if (jsonFinalResponse.status === "failed") {
break;
} else {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}

return redesignedImage ? redesignedImage : "Failed to restore image";
}

0 comments on commit 950d121

Please sign in to comment.