Giter VIP home page Giter VIP logo

srt-parser-2's Introduction

srt-parser-2

An SRT parser for Javascript.

It reads an .srt file into an array.

Install

npm

npm install srt-parser-2

or yarn

yarn add srt-parser-2

Example

This is a srt format file:

1
00:00:11,544 --> 00:00:12,682
Hello

it would become:

[{
    id: '1',
    startTime: '00:00:11,544',
    startSeconds: 11.544,
    endTime: '00:00:12,682',
    endSeconds: 12.682,
    text: 'Hello'
}]

Enviroment support

Since it only process text,
it should work in both Browser and Node.js enviroment

Usage

let srt = `
1
00:00:11,544 --> 00:00:12,682
Hello
`;

import srtParser2 from "srt-parser-2";
var parser = new srtParser2();
var srt_array = parser.fromSrt(srt);
console.log(srt_array);

// turn array back to SRT string.
var srt_string = parser.toSrt(srt_array);
console.log(srt_string);

You can run this example using node example/1.Comma.js

CLI

npx srt-parser-2 -i input.srt -o output.json --minify

Options:

Option Required Default
--input or -i Yes
--output or -o No output.json
--minify No false

License

MIT

Why?

Why this one special? There are plently SRT parser on npm:

What's wrong with them?

Nothing wrong.
All of them can handle this format:

1
00:00:11,544 --> 00:00:12,682
Hello

But I want to handle format like these:

00:00:11.544

This is wrong format, it use period as separator

Or this:

00:00:11,5440

This is also wrong format, millisecond has 4 digit (should be 3)

Or this:

1:00:11,5

Similiar, hour & millisecond is only 1 digit (wrong)

Or this

00:00:00.05

etc

Format Support

Format Other parser srt-parser-2 srt-parser-2 would turn this into
00:00:01,544 Yes ✅ Yes ✅ 00:00:01,544
00:00:01.544 ❓ Yes for some of them Yes ✅ 00:00:01,544
00:00:01.54 ❓ Yes for some of them Yes ✅ 00:00:01,544
00:00:00.3333 No ❌ Yes ✅ 00:00:00,333
00:00:00.3 No ❌ Yes ✅ 00:00:00,300
1:2:3.4 No ❌ Yes ✅ 01:02:03,400

Basic principle:

  1. If hour,minute,second is shorter than 2 digit, pad start with "0", if longer than 2 digit, only save first 2 digit.
  2. Millisecond is the same, but it's 3 digit.
  3. Seperator can be .(periods) or ,(comma), periods(incorrect) will be replace with comma(correct)

Conclusion

  1. Support more time format (even wrong format)
  2. Have extensive test

srt-parser-2's People

Contributors

1c7 avatar ccoenen avatar fedduh avatar naethiel avatar nguerette avatar paudrow avatar pedrospj avatar seadeep42 avatar uriva avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

srt-parser-2's Issues

[Enhancement] Improvements in code

While working on a bug, I had some suggestions I'd like to implement in this lib.

  • Replace mocha / chai with vitest. Vitest is a modern test runner powered by Vite. It runs TS easily.
  • Replace all var statements with let/const
  • Add code documentation (JSDocs) (to see comments if you hover the function)

Are these changes of any interest? If so, I'd be happy to help and open PRs from time to time implementing them.

CLI not working

I use this awesome lib in a personal project. I have only used intalled in the project, today I was trying to use the CLI version and noticed it was not working.

Command I ran:

npx srt-parser-2 -i input.srt -o output.json --minify

Output:

(node:9952) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\Users\ppedr\AppData\Local\npm-cache\_npx\b731975f552886f1\node_modules\srt-parser-2\bin\index.js:4
import { readFile, writeFile } from "fs/promises";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1176:20)
    at Module._compile (node:internal/modules/cjs/loader:1218:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Machine information:
OS: Windows 10
Node: v18.16.0


I'm trying to fix this error and will open a PR if a manage to do it.

Feature request: Add CLI script

I have an SRT file I wanted to quickly parse and output as a JSON.
I was hoping for something like this without creating a new project

npm install -g srt-parser-2
srt-parser-2 -i input.srt -o output.json

It's possible to do this with a bin entry in package.json pointing to a node script.
https://docs.npmjs.com/cli/v7/configuring-npm/package-json#bin

Is this a planned feature or would you be interested in adding it to the package? I can try make a PR for it if needed

feature request: parse the timestamp in seconds

can use this:

const srtTimestampToSeconds = (srtTimestamp) => {
  const [rest, millisecondsString] = srtTimestamp.split(",");
  const milliseconds = parseInt(millisecondsString);
  const [hours, minutes, seconds] = rest.split(":").map(x => parseInt(x));
  return milliseconds * 0.001 + seconds + 60 * minutes + 3600 * hours;
};

Include type definitions?

Thanks for the nice library. It'd be great if you could include type definitions.

As a work around, I'm creating a file in my project called @types/srt-parser-2.d.ts with the following code in it.

export interface Line {
  id: string;
  startTime: string;
  endTime: string;
  text: string;
}
export default class Parser {
  seperator: string;
  correctFormat(time: string): string;
  private fixed_str_digit;
  private tryComma;
  private tryDot;
  fromSrt(data: string): {
      id: string;
      startTime: string;
      endTime: string;
      text: string;
  }[];
  toSrt(data: Array<Line>): string;
}

timestampToSeconds sometimes returns incorrect number

Hi,

I would love to use your library but I noticed some odd javascript rounding behaviour.

In this function

const timestampToSeconds = (srtTimestamp: string) => {
  const [rest, millisecondsString] = srtTimestamp.split(",");
  const milliseconds = parseInt(millisecondsString);
  const [hours, minutes, seconds] = rest.split(":").map((x) => parseInt(x));
  return milliseconds * 0.001 + seconds + 60 * minutes + 3600 * hours;
};

When using the timestamp:

timestampToSeconds('00:01:20,460');

returns: 80.46000000000001

Actual calc is 460 * 0.001 + 20 + 60, which returns 80.46000000000001 in JS

I guess this is a JS perk. But can be overcome by doing some extra rouding in this function.
e.g. Math.round(80.46000000000001 * 1000) / 1000

Another example is this timestamp: 00:01:32,020

Improve how timestamps in seconds are handled

Issue #13 asked for implementing parsing timestamps in seconds, but there is an issue with that: the documentation shows an example of that, but do not explain which of startTime or startSeconds are used when converting back to a string.

One simple improvement is fixing the documentation by making this behavior clear.

Other complex improvement is also allowing to choose between one and other (maybe something like parser.toSrt(srt_array, {useSeconds: true})) and/or exposing a secondsToTimestamp method.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.