File size: 4,491 Bytes
6076169 |
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
"use server";
import getDbConnection from "@/lib/db";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function transcribeUploadedFile(
resp: {
serverData: { userId: string; file: any };
}[],
) {
if (!resp) {
return {
success: false,
message: "File upload failed",
data: null,
};
}
const {
serverData: {
userId,
file: { url: fileUrl, name: fileName },
},
} = resp[0];
if (!fileUrl || !fileName) {
return {
success: false,
message: "File upload failed",
data: null,
};
}
const response = await fetch(fileUrl);
try {
const transcriptions = await openai.audio.transcriptions.create({
model: "whisper-1",
file: response,
});
console.log({ transcriptions });
return {
success: true,
message: "File uploaded successfully!",
data: { transcriptions, userId },
};
} catch (error) {
console.error("Error processing file", error);
if (error instanceof OpenAI.APIError && error.status === 413) {
return {
success: false,
message: "File size exceeds the max limit of 20MB",
data: null,
};
}
return {
success: false,
message: error instanceof Error ? error.message : "Error processing file",
data: null,
};
}
}
async function saveBlogPost(userId: string, title: string, content: string) {
try {
const sql = await getDbConnection();
const [insertedPost] = await sql`
INSERT INTO posts (user_id, title, content)
VALUES (${userId}, ${title}, ${content})
RETURNING id
`;
return insertedPost.id;
} catch (error) {
console.error("Error saving blog post", error);
throw error;
}
}
async function getUserBlogPosts(userId: string) {
try {
const sql = await getDbConnection();
const posts = await sql`
SELECT content FROM posts
WHERE user_id = ${userId}
ORDER BY created_at DESC
LIMIT 3
`;
return posts.map((post) => post.content).join("\n\n");
} catch (error) {
console.error("Error getting user blog posts", error);
throw error;
}
}
async function generateBlogPost({
transcriptions,
userPosts,
}: {
transcriptions: string;
userPosts: string;
}) {
const completion = await openai.chat.completions.create({
messages: [
{
role: "system",
content:
"You are a skilled content writer that converts audio transcriptions into well-structured, engaging blog posts in Markdown format. Create a comprehensive blog post with a catchy title, introduction, main body with multiple sections, and a conclusion. Analyze the user's writing style from their previous posts and emulate their tone and style in the new post. Keep the tone casual and professional.",
},
{
role: "user",
content: `Here are some of my previous blog posts for reference:
${userPosts}
Please convert the following transcription into a well-structured blog post using Markdown formatting. Follow this structure:
1. Start with a SEO friendly catchy title on the first line.
2. Add two newlines after the title.
3. Write an engaging introduction paragraph.
4. Create multiple sections for the main content, using appropriate headings (##, ###).
5. Include relevant subheadings within sections if needed.
6. Use bullet points or numbered lists where appropriate.
7. Add a conclusion paragraph at the end.
8. Ensure the content is informative, well-organized, and easy to read.
9. Emulate my writing style, tone, and any recurring patterns you notice from my previous posts.
Here's the transcription to convert: ${transcriptions}`,
},
],
model: "gpt-4o-mini",
temperature: 0.7,
max_tokens: 1000,
});
return completion.choices[0].message.content;
}
export async function generateBlogPostAction({
transcriptions,
userId,
}: {
transcriptions: { text: string };
userId: string;
}) {
const userPosts = await getUserBlogPosts(userId);
let postId = null;
if (transcriptions) {
const blogPost = await generateBlogPost({
transcriptions: transcriptions.text,
userPosts,
});
if (!blogPost) {
return {
success: false,
message: "Blog post generation failed, please try again...",
};
}
const [title, ...contentParts] = blogPost?.split("\n\n") || [];
//database connection
if (blogPost) {
postId = await saveBlogPost(userId, title, blogPost);
}
}
//navigate
revalidatePath(`/posts/${postId}`);
redirect(`/posts/${postId}`);
}
|