Browse Source

Initial commit

Add files from pridepack.
master
TheoryOfNekomata 1 year ago
commit
d9a32e011a
16 changed files with 4317 additions and 0 deletions
  1. +9
    -0
      .eslintrc
  2. +108
    -0
      .gitignore
  3. +7
    -0
      LICENSE
  4. +52
    -0
      package.json
  5. +3
    -0
      pridepack.json
  6. +9
    -0
      src/config.ts
  7. +24
    -0
      src/index.ts
  8. +31
    -0
      src/modules/summary/SummaryController.ts
  9. +72
    -0
      src/modules/summary/SummaryService.ts
  10. +2
    -0
      src/modules/summary/index.ts
  11. +30
    -0
      src/routes.ts
  12. +9
    -0
      src/server.ts
  13. +28
    -0
      test/index.test.ts
  14. +21
    -0
      tsconfig.eslint.json
  15. +21
    -0
      tsconfig.json
  16. +3891
    -0
      yarn.lock

+ 9
- 0
.eslintrc View File

@@ -0,0 +1,9 @@
{
"root": true,
"extends": [
"lxsmnsyc/typescript"
],
"parserOptions": {
"project": "./tsconfig.eslint.json"
}
}

+ 108
- 0
.gitignore View File

@@ -0,0 +1,108 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc
.idea/

+ 7
- 0
LICENSE View File

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2023 TheoryOfNekomata <allan.crisostomo@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 52
- 0
package.json View File

@@ -0,0 +1,52 @@
{
"name": "webvideo-transcript-summary-web-api",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=12"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^18.14.1",
"eslint": "^8.35.0",
"eslint-config-lxsmnsyc": "^0.5.0",
"pridepack": "2.4.4",
"tslib": "^2.5.0",
"typescript": "^4.9.5",
"vitest": "^0.28.1"
},
"dependencies": {
"fastify": "^4.12.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"lint": "pridepack lint",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": false,
"description": "Get transcript summaries of Web videos.",
"repository": {
"url": "https://code.modal.sh/modal-soft/webvideo-transcript-summary-web-api",
"type": "git"
},
"homepage": "https://code.modal.sh/modal-soft/webvideo-transcript-summary-web-api",
"bugs": {
"url": "https://code.modal.sh/modal-soft/webvideo-transcript-summary-web-api/issues"
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
}
}

+ 3
- 0
pridepack.json View File

@@ -0,0 +1,3 @@
{
"target": "es2018"
}

+ 9
- 0
src/config.ts View File

@@ -0,0 +1,9 @@
export namespace meta {
export const port = Number(process.env.PORT ?? 8080);
export const host = process.env.HOST ?? '0.0.0.0';
}

export namespace openai {
export const apiKey = process.env.OPENAI_API_KEY as string;
export const organizationId = process.env.OPENAI_ORGANIZATION_ID;
}

+ 24
- 0
src/index.ts View File

@@ -0,0 +1,24 @@
import * as config from './config';
import { createServer } from './server';

import { addHealthRoutes, addSummaryRoutes } from './routes';

const server = createServer({
logger: process.env.NODE_ENV !== 'test',
});

addHealthRoutes(server);
addSummaryRoutes(server);

server.listen(
{
port: config.meta.port,
host: config.meta.host,
},
(err) => {
if (err) {
server.log.error(err.message);
process.exit(1);
}
}
);

+ 31
- 0
src/modules/summary/SummaryController.ts View File

@@ -0,0 +1,31 @@
import { CreateSummarizerParams } from '@modal-sh/webvideo-transcript-summary-core';
import { SummaryService, SummaryServiceImpl } from './SummaryService';
import * as config from '../../config';
import { RouteHandlerMethod } from 'fastify';

export interface SummaryController {
summarizeVideoTranscript: RouteHandlerMethod;
}

export class SummaryControllerImpl implements SummaryController {
constructor(
private readonly summaryService: SummaryService = new SummaryServiceImpl(
config.openai.apiKey,
config.openai.organizationId,
),
) {
// noop
}

readonly summarizeVideoTranscript: RouteHandlerMethod = async (request, reply) => {
const params = request.body as CreateSummarizerParams;
try {
const summaryResult = await this.summaryService.summarizeVideoTranscript(params);
reply.send(summaryResult);
} catch {
reply
.code(500)
.send();
}
};
}

+ 72
- 0
src/modules/summary/SummaryService.ts View File

@@ -0,0 +1,72 @@
import {
createSummarizer,
CreateSummarizerParams,
VideoType,
} from '@modal-sh/webvideo-transcript-summary-core';

export interface SummaryResult {
summary: string;
normalizedTranscript: string;
rawTranscript: string;
}

export interface SummaryService {
summarizeVideoTranscript(params: CreateSummarizerParams): Promise<Partial<SummaryResult>>
}

export class SummaryServiceImpl implements SummaryService {
constructor(
private readonly openAiApiKey: string,
private readonly openAiOrganizationId?: string,
) {
// noop
}

summarizeVideoTranscript(params: CreateSummarizerParams) {
return new Promise<Partial<SummaryResult>>((resolve, reject) => {
let successEvent = {} as Partial<SummaryResult>;
let error: Error;
const summarizer = createSummarizer({
type: VideoType.YOUTUBE,
url: params.url,
openaiApiKey: this.openAiApiKey,
openaiOrganizationId: this.openAiOrganizationId,
});

summarizer.on('process', (data) => {
if (data.phase === 'success') {
switch (data.processType) {
case 'fetch-transcript':
successEvent.rawTranscript = (
JSON.parse(data.content) as { text: string }[]
)
.map((item) => item.text).join(' ');
break;
case 'normalize-transcript':
successEvent.normalizedTranscript = data.content as string;
break;
case 'summarize-transcript':
successEvent.summary = data.content as string;
break;
default:
break;
}
}
});

summarizer.on('error', (err) => {
error = err;
});

summarizer.on('end', () => {
if (error) {
reject(error);
return;
}
resolve(successEvent);
});

summarizer.process();
});
}
}

+ 2
- 0
src/modules/summary/index.ts View File

@@ -0,0 +1,2 @@
export * from './SummaryController';
export * from './SummaryService';

+ 30
- 0
src/routes.ts View File

@@ -0,0 +1,30 @@
import { FastifyInstance } from 'fastify';
import { SummaryController, SummaryControllerImpl } from './modules/summary';

export const addHealthRoutes = (server: FastifyInstance) => {
server
.route({
method: 'GET',
url: '/api/health/live',
handler: async (_, reply) => {
reply.send({ status: 'ok' });
},
})
.route({
method: 'GET',
url: '/api/health/ready',
handler: async (_, reply) => {
reply.send({ status: 'ok' });
},
});
}

export const addSummaryRoutes = (server: FastifyInstance) => {
const summaryController: SummaryController = new SummaryControllerImpl();
server
.route({
method: 'POST',
url: '/api/summary',
handler: summaryController.summarizeVideoTranscript,
});
};

+ 9
- 0
src/server.ts View File

@@ -0,0 +1,9 @@
import fastify from 'fastify';

export interface CreateServerOptions {
logger?: boolean;
}

export const createServer = (options = {} as CreateServerOptions) => fastify({
logger: options?.logger ?? false,
});

+ 28
- 0
test/index.test.ts View File

@@ -0,0 +1,28 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createServer } from '../src/server';
import { addHealthRoutes, addSummaryRoutes } from '../src/routes';
import { FastifyInstance } from 'fastify';

describe('Example', () => {
let server: FastifyInstance;

beforeAll(() => {
server = createServer();
addHealthRoutes(server);
addSummaryRoutes(server);
});

afterAll(async () => {
await server.close();
});

it('should have the expected content', async () => {
const response = await server
.inject()
.get('/api/health/live')
.headers({
Accept: 'application/json',
});
expect(response.statusCode).toBe(200);
});
});

+ 21
- 0
tsconfig.eslint.json View File

@@ -0,0 +1,21 @@
{
"exclude": ["node_modules"],
"include": ["src", "types", "test"],
"compilerOptions": {
"module": "ESNext",
"lib": ["DOM", "ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018"
}
}

+ 21
- 0
tsconfig.json View File

@@ -0,0 +1,21 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018"
}
}

+ 3891
- 0
yarn.lock
File diff suppressed because it is too large
View File


Loading…
Cancel
Save