guessit-js 4.11.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,7 @@ Extract metadata (title, year, season, episode, codec, language, etc.) from medi
13
13
  ## Features
14
14
 
15
15
  - **Runs 2191 of the 2229 cases in Python guessit's own test suite** (upstream 4.5.1, its corpus *and* its per-rule files) — and is **more correct**: fixes for 32 historical upstream bugs, Python's still-open #877, and 114 of the 276 cross-parser cases Python admits failing (see [Differences from Python](#differences-from-python-guessit))
16
+ - **Drop-in output**: results use Python guessit's own notation (`"language": "French"`, `"country": "UNITED STATES"`, `"date": "2024-03-15"`) in the library, CLI, REST API and WASM; guessit-js only *parses* better. Richer codes are opt-in with [`output: 'codes'`](#output-notation)
16
17
  - **~2x faster** than Python per parse ([measured](#performance))
17
18
  - **56 properties** detected: title, year, season, episode, resolution, codec, language, ids, and more — with a [machine-readable schema](#output-schema)
18
19
  - **Batch parsing**: `guessitMany()` in-process, or one POST for up to 100 names
@@ -90,6 +91,34 @@ guessit('X2.2003.720p.DSNP.WEB-DL.DDP5.1.H.264-EVO.mkv');
90
91
  // streaming_service: 'Disney+', source: 'Web', ... }
91
92
  ```
92
93
 
94
+ ### Output notation
95
+
96
+ Results are a drop-in for Python guessit: the same keys and the same notation
97
+ Python's `guessit --json` prints, so code written against Python guessit keeps
98
+ working. guessit-js parses many names better (see
99
+ [Differences](#differences-from-python-guessit)); it never formats differently
100
+ by default.
101
+
102
+ | Value | default (`output: 'python'`) | `output: 'codes'` |
103
+ |---|---|---|
104
+ | `language`, `subtitle_language` | `"French"`, `["German", "Multiple languages"]` | `{ alpha3: 'fra' }`, `[{ alpha3: 'deu' }, { alpha3: 'mul' }]` |
105
+ | region / script | dropped, as in Python: `"Portuguese"` | kept: `{ alpha3: 'por', country: 'BR' }` |
106
+ | `country` | `"UNITED STATES"` | `"US"` |
107
+ | `date` | `"2024-03-15"` | `Date` (JSON: `"2024-03-15T00:00:00.000Z"`) |
108
+
109
+ ```typescript
110
+ guessit('Movie.2020.PT-BR.1080p.mkv');
111
+ // { title: 'Movie', year: 2020, language: 'Portuguese', ... }
112
+ guessit('Movie.2020.PT-BR.1080p.mkv', { output: 'codes' });
113
+ // { title: 'Movie', year: 2020, language: { alpha3: 'por', country: 'BR' }, ... }
114
+ ```
115
+
116
+ The same switch exists everywhere: `?output=codes` or `"options": {"output": "codes"}`
117
+ on the REST API, `--output-codes` on the CLI, `{"options": {"output": "codes"}}`
118
+ for WASM. The names are generated from babelfish, the library Python guessit uses
119
+ (`scripts/python-names.py`). `toPythonNotation()`, `pythonLanguageName()` and
120
+ `pythonCountryName()` are exported for converting codes yourself.
121
+
93
122
  ### Batch
94
123
 
95
124
  `guessitMany()` parses a list in one pass. `guessit()` re-parses the options and
@@ -129,6 +158,7 @@ guessit('file.mkv', { type: 'episode' });
129
158
  guessit('my 720p show S01E02', { expected_title: ['my 720p show'] });
130
159
  guessit('file.mkv', { allowed_languages: ['en', 'fr'] });
131
160
  guessit('file.mkv', { excludes: ['release_group'] });
161
+ guessit('file.mkv', { output: 'codes' }); // guessit-js codes instead of Python names
132
162
  ```
133
163
 
134
164
  ```typescript
@@ -203,6 +233,9 @@ curl -X POST http://localhost:3847/api/guessit \
203
233
  ```
204
234
 
205
235
  CLI parsing flags become server defaults: `guessit-js --serve -t episode -L en`.
236
+ Every surface answers in Python guessit's notation; add `?output=codes` (GET) or
237
+ `"options": {"output": "codes"}` (POST) for guessit-js codes
238
+ ([Output notation](#output-notation)). Any other `output` value is a `400`.
206
239
  The repo also ships a fuller dev server (`npm start`) with the demo page,
207
240
  Swagger UI at `/docs`, and static WASM serving.
208
241
 
@@ -227,6 +260,7 @@ For non-JS environments (Rust, Go, C++, edge compute). Uses [Javy](https://githu
227
260
  ```bash
228
261
  npm run wasm
229
262
  echo '{"filename":"Movie.2024.1080p.mkv"}' | wasmtime wasm/guessit.wasm
263
+ echo '{"filename":"Movie.PT-BR.mkv","options":{"output":"codes"}}' | wasmtime wasm/guessit.wasm
230
264
  ```
231
265
 
232
266
  The WASM build is **bit-identical to the JS build** across the entire test corpus
@@ -238,6 +272,13 @@ and as the npm package [`@opensubtitles/guessit-wasm`](packages/guessit-wasm)
238
272
  (`guessit.wasm` + a small `node:wasi` helper). Binaries are never committed to git.
239
273
  `wasm/build.sh` downloads Javy pinned by version **and** sha256.
240
274
 
275
+ ### Versioning
276
+
277
+ One version number for everything built from a release tag: the `guessit-js`
278
+ npm package, `@opensubtitles/guessit-wasm`, the WASM binaries on the GitHub
279
+ release, the Docker image (`ghcr.io/opensubtitles/guessit-js:<version>`) and the
280
+ hosted API (`/api/health` reports it).
281
+
241
282
  ## Differences from Python guessit
242
283
 
243
284
  guessit-js is a faithful port (tracking Python 4.5.4, plus the unreleased
package/bin/cli.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  import { readFileSync, existsSync } from 'fs';
7
7
  import { homedir } from 'os';
8
8
  import { join } from 'path';
9
- import { guessit, guessitMany, properties as apiProperties, version } from '../dist/guessit-js.js';
9
+ import { guessit, guessitMany, properties as apiProperties, version, pythonLanguageName, pythonCountryName } from '../dist/guessit-js.js';
10
10
 
11
11
  // Parsing cost grows with the square of the number of matches a name yields, so
12
12
  // a long synthetic string costs far more than its length suggests: 400
@@ -23,8 +23,6 @@ const MAX_BATCH = 100;
23
23
  // Python's GuessitEncoder emits babelfish `.name` in JSON ("English",
24
24
  // "UNITED STATES") while YAML uses str() ("en", "pt-BR", "US"). Mirror both.
25
25
  const ALPHA3_TO_2 = {"eng":"en","fra":"fr","deu":"de","spa":"es","ita":"it","por":"pt","rus":"ru","jpn":"ja","zho":"zh","kor":"ko","ara":"ar","hin":"hi","tur":"tr","pol":"pl","nld":"nl","swe":"sv","dan":"da","nor":"no","fin":"fi","hun":"hu","ces":"cs","ron":"ro","ukr":"uk","heb":"he","cat":"ca","vie":"vi","tha":"th","ind":"id","mal":"ml","tel":"te","tam":"ta","bul":"bg","hrv":"hr","srp":"sr","slk":"sk","slv":"sl","ell":"el","lit":"lt","lav":"lv","est":"et","glg":"gl","eus":"eu","ben":"bn","isl":"is","mkd":"mk","bos":"bs","alb":"sq","per":"fa","msa":"ms","mon":"mn","urd":"ur","pan":"pa","guj":"gu","kan":"kn","mar":"mr","asm":"as","mya":"my","khm":"km","lao":"lo"};
26
- const LANGUAGE_NAMES = {"eng":"English","fra":"French","deu":"German","spa":"Spanish","ita":"Italian","por":"Portuguese","rus":"Russian","jpn":"Japanese","zho":"Chinese","kor":"Korean","ara":"Arabic","hin":"Hindi","tur":"Turkish","pol":"Polish","nld":"Dutch","swe":"Swedish","dan":"Danish","nor":"Norwegian","fin":"Finnish","hun":"Hungarian","ces":"Czech","ron":"Romanian","ukr":"Ukrainian","heb":"Hebrew","cat":"Catalan","vie":"Vietnamese","tha":"Thai","ind":"Indonesian","mal":"Malayalam","tel":"Telugu","tam":"Tamil","bul":"Bulgarian","hrv":"Croatian","srp":"Serbian","slk":"Slovak","slv":"Slovenian","ell":"Greek","lit":"Lithuanian","lav":"Latvian","est":"Estonian","glg":"Galician","eus":"Basque","ben":"Bengali","isl":"Icelandic","mkd":"Macedonian","bos":"Bosnian","alb":"Albanian","per":"Persian","msa":"Malay","mon":"Mongolian","urd":"Urdu","pan":"Punjabi","guj":"Gujarati","kan":"Kannada","mar":"Marathi","asm":"Assamese","mya":"Burmese","khm":"Khmer","lao":"Lao"};
27
- const COUNTRY_NAMES = {"US":"UNITED STATES","GB":"UNITED KINGDOM","AU":"AUSTRALIA","CA":"CANADA","NZ":"NEW ZEALAND","IE":"IRELAND","FR":"FRANCE","DE":"GERMANY","ES":"SPAIN","IT":"ITALY","BR":"BRAZIL","PT":"PORTUGAL","RU":"RUSSIAN FEDERATION","JP":"JAPAN","CN":"CHINA","TW":"TAIWAN, PROVINCE OF CHINA","HK":"HONG KONG","KR":"KOREA, REPUBLIC OF","IN":"INDIA","MX":"MEXICO","NL":"NETHERLANDS","SE":"SWEDEN","NO":"NORWAY","DK":"DENMARK","FI":"FINLAND","PL":"POLAND","CH":"SWITZERLAND","AT":"AUSTRIA","BE":"BELGIUM","CZ":"CZECHIA","GR":"GREECE","HU":"HUNGARY","RO":"ROMANIA","TR":"TURKEY","UA":"UKRAINE","AR":"ARGENTINA","ZA":"SOUTH AFRICA"};
28
26
 
29
27
  const HELP = `usage: guessit-js [options] [filename ...]
30
28
 
@@ -79,6 +77,10 @@ Information:
79
77
  --version Display the guessit-js version banner
80
78
 
81
79
  Extras (not in the Python CLI):
80
+ --output-codes JSON with guessit-js codes instead of Python's names:
81
+ languages as {"alpha3": ...} (keeps regions such as
82
+ pt-BR), countries as ISO alpha-2, dates as ISO strings.
83
+ --serve: ?output=codes or {"options": {"output": "codes"}}
82
84
  --serve [PORT] Start a REST API server (default port 3847;
83
85
  GET /api/guessit?filename=..., POST {filename|filenames})
84
86
  --benchmark [N] Parse the given filenames N times (default 1000)
@@ -195,6 +197,7 @@ for (let i = 0; i < args.length; i++) {
195
197
  case '--no-default-config': cliOptions.no_default_config = true; break;
196
198
  case '-p': case '--properties': listProperties = true; break;
197
199
  case '-V': case '--values': listValues = true; break;
200
+ case '--output-codes': cliOptions.output = 'codes'; break;
198
201
  case '--serve':
199
202
  serve = true;
200
203
  if (args[i + 1] && /^\d+$/.test(args[i + 1])) { servePort = Number(args[++i]); }
@@ -234,9 +237,25 @@ if (!noUserConfig) {
234
237
 
235
238
  // Precedence: user/explicit config < CLI flags.
236
239
  const options = { ...configOptions, ...cliOptions };
240
+ // The CLI renders Python's notation itself (JSON names, YAML str() codes), so it
241
+ // always asks the library for codes and converts at display time.
242
+ const requestedOutput = options.output === 'codes' ? 'codes' : 'python';
237
243
  for (const key of ['allowed_languages', 'allowed_countries', 'expected_title', 'expected_group', 'includes', 'excludes']) {
238
244
  if (configOptions[key] && cliOptions[key]) options[key] = [...configOptions[key], ...cliOptions[key]];
239
245
  }
246
+ options.output = 'codes';
247
+
248
+ // A result in the notation the caller asked for. Codes go out as the library
249
+ // returns them (JSON turns Date into an ISO string); Python notation is rendered
250
+ // here, as Python's own CLI would.
251
+ function render(result, want, mode = 'json') {
252
+ return want === 'codes' ? JSON.parse(JSON.stringify(result)) : display(result, mode);
253
+ }
254
+ function wantedOutput(value) {
255
+ if (value === undefined || value === null || value === '' || value === 'python') return 'python';
256
+ if (value === 'codes') return 'codes';
257
+ throw new Error(`invalid output "${value}": must be "python" or "codes"`);
258
+ }
240
259
 
241
260
  if (options.type && options.type !== 'movie' && options.type !== 'episode') {
242
261
  fail(`invalid --type "${options.type}": must be movie or episode`);
@@ -254,14 +273,14 @@ function display(v, mode, key) {
254
273
  const base = ALPHA3_TO_2[v.alpha3] || v.alpha3;
255
274
  return v.country ? `${base}-${v.country}` : base;
256
275
  }
257
- return LANGUAGE_NAMES[v.alpha3] || v.alpha3;
276
+ return pythonLanguageName(v.alpha3);
258
277
  }
259
278
  const out = {};
260
279
  for (const [k, val] of Object.entries(v)) out[k] = display(val, mode, k);
261
280
  return out;
262
281
  }
263
282
  if (key === 'country' && typeof v === 'string' && mode !== 'yaml') {
264
- return COUNTRY_NAMES[v] || v;
283
+ return pythonCountryName(v);
265
284
  }
266
285
  return v;
267
286
  }
@@ -402,7 +421,10 @@ if (serve) {
402
421
  const opts = { ...baseOptions };
403
422
  const type = url.searchParams.get('type');
404
423
  if (type === 'movie' || type === 'episode') opts.type = type;
405
- try { sendJson(res, 200, display(guessit(filename, opts), 'json')); }
424
+ let want;
425
+ try { want = wantedOutput(url.searchParams.get('output') ?? requestedOutput); }
426
+ catch (e) { sendJson(res, 400, { error: e.message }); return; }
427
+ try { sendJson(res, 200, render(guessit(filename, opts), want)); }
406
428
  catch (e) { sendJson(res, 500, { error: String((e && e.message) || e) }); }
407
429
  return;
408
430
  }
@@ -413,7 +435,8 @@ if (serve) {
413
435
  req.on('end', () => {
414
436
  try {
415
437
  const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
416
- const opts = { ...baseOptions, ...(body.options || {}) };
438
+ const want = wantedOutput((body.options && body.options.output) ?? requestedOutput);
439
+ const opts = { ...baseOptions, ...(body.options || {}), output: 'codes' };
417
440
  if (Array.isArray(body.filenames)) {
418
441
  if (body.filenames.length > MAX_BATCH) {
419
442
  sendJson(res, 413, { error: `Max ${MAX_BATCH} filenames per request` });
@@ -429,7 +452,7 @@ if (serve) {
429
452
  // guessitMany parses the options once and isolates a name that throws.
430
453
  sendJson(res, 200, guessitMany(names, opts).map((entry) => (
431
454
  'result' in entry
432
- ? { input_string: entry.input_string, result: display(entry.result, 'json') }
455
+ ? { input_string: entry.input_string, result: render(entry.result, want) }
433
456
  : entry
434
457
  )));
435
458
  } else if (typeof body.filename === 'string') {
@@ -437,7 +460,7 @@ if (serve) {
437
460
  sendJson(res, 413, { error: `filename exceeds ${MAX_FILENAME_LENGTH} characters` });
438
461
  return;
439
462
  }
440
- sendJson(res, 200, display(guessit(body.filename, opts), 'json'));
463
+ sendJson(res, 200, render(guessit(body.filename, opts), want));
441
464
  } else {
442
465
  sendJson(res, 400, { error: 'Body must contain "filename" (string) or "filenames" (array)' });
443
466
  }
@@ -486,7 +509,7 @@ for (const filename of filenames) {
486
509
  result = {};
487
510
  for (const [k, v] of Object.entries(raw)) result[k] = simplifyAdvanced(v);
488
511
  } else {
489
- result = display(raw, output === 'yaml' ? 'yaml' : 'json');
512
+ result = output === 'yaml' ? display(raw, 'yaml') : render(raw, requestedOutput);
490
513
  }
491
514
  } catch (e) {
492
515
  hadError = true;