|
| 1 | +import { nanoid } from 'nanoid'; |
| 2 | +import { z } from 'zod'; |
| 3 | + |
1 | 4 | const baseUrl = 'https://www.summarize.tech/api/summary';
|
2 | 5 |
|
3 | 6 | // Example usage:
|
4 | 7 | // const videoUrl = 'https://www.youtube.com/watch?v=ruUlK6zRwS8';
|
5 | 8 | // const summary = await getVideoSummary(videoUrl);
|
6 | 9 | // console.log({ summary });
|
7 | 10 |
|
8 |
| -type SummaryResponse = { |
9 |
| - rollups: Record<number, SummaryChunk>; |
10 |
| - title: string; |
11 |
| -}; |
12 |
| - |
13 |
| -type SummaryChunk = { |
14 |
| - children: Record<number, string>; |
15 |
| - summary: string; |
16 |
| -}; |
17 |
| - |
18 |
| -const makeId = (length: number) => { |
19 |
| - let result = ''; |
20 |
| - const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'; |
21 |
| - const charactersLength = characters.length; |
22 |
| - |
23 |
| - for (let i = 0; i < length; i++) |
24 |
| - result += characters.charAt(Math.floor(Math.random() * charactersLength)); |
25 |
| - |
26 |
| - return result; |
27 |
| -}; |
| 11 | +const summarySchema = z.object({ |
| 12 | + title: z.string(), |
| 13 | + rollups: z.record( |
| 14 | + z.coerce.number().int().gte(0), |
| 15 | + z.object({ |
| 16 | + children: z.record(z.coerce.number().int().gte(0), z.string()), |
| 17 | + summary: z.object({ |
| 18 | + before: z.string(), |
| 19 | + keyword: z.string(), |
| 20 | + after: z.string(), |
| 21 | + }), |
| 22 | + }), |
| 23 | + ), |
| 24 | +}); |
28 | 25 |
|
29 |
| -export const getVideoSummary = async (videoUrl: string) => { |
30 |
| - return await fetch(baseUrl, { |
| 26 | +export const getVideoSummary = async (videoUrl: string) => |
| 27 | + fetch(baseUrl, { |
31 | 28 | method: 'POST',
|
32 |
| - body: JSON.stringify({ url: videoUrl, deviceId: makeId(21) }), |
| 29 | + body: JSON.stringify({ url: videoUrl, deviceId: nanoid(21) }), |
33 | 30 | headers: { 'content-type': 'application/json' },
|
34 | 31 | })
|
35 | 32 | .then((res) => res.json())
|
36 |
| - .then((res) => |
37 |
| - (Object.values((res as SummaryResponse).rollups) ?? []) |
38 |
| - .map((chunk) => chunk.summary) |
39 |
| - .join(' '), |
| 33 | + .then((json) => summarySchema.parse(json)) |
| 34 | + .then((result) => |
| 35 | + Object.values(result.rollups) |
| 36 | + .map(({ summary }) => summary.before + summary.keyword + summary.after) |
| 37 | + .join('\n') |
| 38 | + .replace(/\. /g, '.\n'), |
40 | 39 | );
|
41 |
| -}; |
0 commit comments