Skip to content

Commit

Permalink
feat: support timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Mar 2, 2023
1 parent fda8168 commit 4cee6c9
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 19 deletions.
41 changes: 41 additions & 0 deletions components/Sentence.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export default function Sentence({
bvId,
sentence,
}: {
bvId: string;
sentence: string;
}) {
const baseUrl = `https://www.bilibili.com/video/${bvId}`;

const matchResult = sentence.match(/\s*(\d+\.\d+)(.*)/);
let timestamp: string | undefined;
if (matchResult) {
console.log("========matchResult========", matchResult);
const seconds = Number(matchResult[1]);
const hours = Math.floor(seconds / 3600);
const remainingSeconds = Math.floor(seconds % 3600);
const minutes = Math.floor(remainingSeconds / 60);
const remainingMinutes = Math.floor(remainingSeconds % 60);
if (hours > 0) {
timestamp = `${hours}:${minutes
.toString()
.padStart(2, "0")}:${remainingMinutes.toString().padStart(2, "0")}`;
} else {
timestamp = `${minutes}:${remainingMinutes.toString().padStart(2, "0")}`;
}

const content = matchResult[2];
return (
<li className="mb-2 list-disc">
<a
href={`${baseUrl}/?t=${encodeURIComponent(timestamp)}`}
className="text-sky-400 hover:text-sky-600"
>
{timestamp}
</a>
{`${content?.startsWith(":") ? content.substring(1) : content}`}
</li>
);
}
return <li className="mb-2 list-disc">{sentence}</li>;
}
5 changes: 5 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import type { NextFetchEvent, NextRequest } from "next/server";
import { Redis } from "@upstash/redis";
import { Ratelimit } from "@upstash/ratelimit";
import { isDev } from "./utils/env";

const redis = Redis.fromEnv();

Expand All @@ -16,6 +17,10 @@ const ratelimit = new Ratelimit({
});

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
if (isDev) {
return NextResponse.next();
}

const { bvId, apiKey } = await req.json();
const result = await redis.get<string>(bvId);
if (result) {
Expand Down
33 changes: 17 additions & 16 deletions pages/[...slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { toast, Toaster } from "react-hot-toast";
import { useLocalStorage } from "react-use";
import Sentence from "../components/Sentence";
import SquigglyLines from "../components/SquigglyLines";
import { useSummarize } from "../hooks/useSummarize";

Expand Down Expand Up @@ -77,6 +78,19 @@ export const Home: NextPage = () => {
await generateSummary();
};

const handleCopy = () => {
if (!isSecureContext) {
toast("复制错误", {
icon: "❌",
});
return;
}
navigator.clipboard.writeText(summary + "\n\n via #BiliGPT b.jimmylv.cn");
toast("复制成功", {
icon: "✂️",
});
};

return (
<>
<a
Expand Down Expand Up @@ -215,26 +229,13 @@ export const Home: NextPage = () => {
</a>
</h3>
<div
className="mx-auto mt-6 max-w-3xl cursor-copy rounded-xl border bg-white p-4 text-lg leading-7 shadow-md transition hover:bg-gray-50"
onClick={() => {
if (!isSecureContext) {
toast("复制错误", {
icon: "❌",
});
return;
}
navigator.clipboard.writeText(
summary + "\n\n via #BiliGPT b.jimmylv.cn"
);
toast("复制成功", {
icon: "✂️",
});
}}
className="mx-auto mt-6 max-w-3xl rounded-xl border bg-white p-4 text-lg leading-7 shadow-md transition hover:bg-gray-50"
// onClick={handleCopy}
>
{summary.split("- ").map((sentence, index) => (
<div key={index}>
{sentence.length > 0 && (
<li className="mb-2 list-disc">{sentence}</li>
<Sentence bvId={currentBvId} sentence={sentence} />
)}
</div>
))}
Expand Down
6 changes: 4 additions & 2 deletions pages/api/summarize.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { Redis } from "@upstash/redis";
import type { NextFetchEvent, NextRequest } from "next/server";
import { isDev } from "../../utils/env";
import { OpenAIResult } from "../../utils/OpenAIResult";
import { getChunckedTranscripts, getSummaryPrompt } from "../../utils/prompt";

Expand Down Expand Up @@ -47,9 +48,8 @@ export default async function handler(
// @ts-ignore
const transcripts = subtitles.body.map((item, index) => {
return {
text: item.content,
text: `${item.from}: ${item.content}`,
index,
timestamp: item.from,
};
});
// console.log("========transcripts========", transcripts);
Expand All @@ -58,6 +58,7 @@ export default async function handler(

try {
apiKey && console.log("========use user key========");
isDev && console.log("prompt", prompt);
const payload = {
model: "gpt-3.5-turbo",
messages: [{ role: "user" as const, content: prompt }],
Expand All @@ -71,6 +72,7 @@ export default async function handler(
};

const result = await OpenAIResult(payload, apiKey);
// TODO: add better logging when dev or prod
console.log("result", result);
const redis = Redis.fromEnv();
const data = await redis.set(bvId, result);
Expand Down
1 change: 1 addition & 0 deletions utils/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const isDev = process.env.NODE_ENV === "development";
2 changes: 1 addition & 1 deletion utils/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export function getSummaryPrompt(title: string,transcript: any) {
.replace(/\n+/g, " ")
.trim()}"\n视频字幕: "${truncateTranscript(transcript)
.replace(/\n+/g, " ")
.trim()}"\n我希望你是一名专业的视频内容编辑,帮我总结视频的内容精华。请你将视频字幕文本进行总结,然后以无序列表的方式返回,不要超过5条。记得不要重复句子,确保所有的句子都足够精简,清晰完整,祝你好运!`;
.trim()}"\n我希望你是一名专业的视频内容编辑,帮我总结视频的内容精华。请先用一句简短的话总结视频梗概。然后再请你将视频字幕文本进行总结,在每句话的最前面加上时间戳,然后以无序列表的方式返回,不要超过5条。记得不要重复句子,确保所有的句子都足够精简,清晰完整,祝你好运!`;
}

// Seems like 15,000 bytes is the limit for the prompt
Expand Down

0 comments on commit 4cee6c9

Please sign in to comment.