upres-cli 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,665 @@
1
+ #!/usr/bin/env node
2
+ #!/usr/bin/env node
3
+
4
+ // src/cli.ts
5
+ import fs2 from "fs";
6
+ import path2 from "path";
7
+
8
+ // src/client.ts
9
+ import fs from "fs";
10
+ import path from "path";
11
+ import os from "os";
12
+ var DEFAULT_BASE_URL = "https://api.upres.ai/v1";
13
+ var CONFIG_PATH = path.join(os.homedir(), ".config", "upres", "config.json");
14
+ var TUS_CHUNK_SIZE = 5 * 1024 * 1024;
15
+ var LARGE_FILE_THRESHOLD = 50 * 1024 * 1024;
16
+ function loadConfigFile() {
17
+ try {
18
+ if (fs.existsSync(CONFIG_PATH)) {
19
+ return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8"));
20
+ }
21
+ } catch {
22
+ }
23
+ return {};
24
+ }
25
+ function resolveApiKey(override) {
26
+ const key = override ?? process.env.UPRES_API_KEY ?? loadConfigFile().apiKey;
27
+ if (!key) {
28
+ console.error(
29
+ "Error: No API key found.\n Set UPRES_API_KEY env var, pass --api-key, or save to ~/.config/upres/config.json\n Get a key at https://upres.ai/account/api-keys"
30
+ );
31
+ process.exit(1);
32
+ }
33
+ return key;
34
+ }
35
+ var UpresClient = class {
36
+ apiKey;
37
+ baseUrl;
38
+ constructor(config = {}) {
39
+ this.apiKey = resolveApiKey(config.apiKey);
40
+ this.baseUrl = config.baseUrl ?? process.env.UPRES_BASE_URL ?? DEFAULT_BASE_URL;
41
+ }
42
+ async request(method, endpoint, body, headers) {
43
+ const res = await fetch(`${this.baseUrl}${endpoint}`, {
44
+ method,
45
+ headers: {
46
+ Authorization: `Bearer ${this.apiKey}`,
47
+ ...body && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {},
48
+ ...headers
49
+ },
50
+ body: body instanceof FormData ? body : body ? JSON.stringify(body) : void 0
51
+ });
52
+ if (!res.ok) {
53
+ const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
54
+ if (res.status === 401) {
55
+ console.error(`Error: Invalid API key. Get a new key at https://upres.ai/account/api-keys`);
56
+ process.exit(1);
57
+ }
58
+ if (res.status === 402) {
59
+ console.error(
60
+ `Error: Monthly quota exceeded (used ${err.used ?? "?"}/${err.quota ?? "?"}).
61
+ Upgrade to Business tier at https://upres.ai/pricing`
62
+ );
63
+ process.exit(1);
64
+ }
65
+ if (res.status === 429) {
66
+ console.error(`Error: Rate limit exceeded (60 req/min). Wait a moment and retry.`);
67
+ process.exit(1);
68
+ }
69
+ throw new Error(err.error ?? `HTTP ${res.status}`);
70
+ }
71
+ if (res.status === 204) return void 0;
72
+ return res.json();
73
+ }
74
+ /** Upload a file using TUS resumable protocol for files >50MB */
75
+ async tusUpload(filePath, filename) {
76
+ const fileSize = fs.statSync(filePath).size;
77
+ const createRes = await fetch(`${this.baseUrl.replace("/v1", "")}/api/tus`, {
78
+ method: "POST",
79
+ headers: {
80
+ Authorization: `Bearer ${this.apiKey}`,
81
+ "Tus-Resumable": "1.0.0",
82
+ "Upload-Length": String(fileSize),
83
+ "Upload-Metadata": `filename ${Buffer.from(filename).toString("base64")}`,
84
+ "Content-Length": "0"
85
+ }
86
+ });
87
+ if (!createRes.ok) {
88
+ throw new Error(`TUS create failed: HTTP ${createRes.status}`);
89
+ }
90
+ const uploadUrl = createRes.headers.get("Location");
91
+ if (!uploadUrl) throw new Error("TUS server did not return upload URL");
92
+ const stream = fs.createReadStream(filePath, { highWaterMark: TUS_CHUNK_SIZE });
93
+ let offset = 0;
94
+ for await (const chunk of stream) {
95
+ const patchRes = await fetch(uploadUrl, {
96
+ method: "PATCH",
97
+ headers: {
98
+ Authorization: `Bearer ${this.apiKey}`,
99
+ "Tus-Resumable": "1.0.0",
100
+ "Content-Type": "application/offset+octet-stream",
101
+ "Upload-Offset": String(offset),
102
+ "Content-Length": String(chunk.length)
103
+ },
104
+ body: chunk
105
+ });
106
+ if (!patchRes.ok) throw new Error(`TUS patch failed at offset ${offset}: HTTP ${patchRes.status}`);
107
+ offset += chunk.length;
108
+ }
109
+ const uploadId = uploadUrl.split("/").pop();
110
+ return `${this.baseUrl.replace("/v1", "")}/api/tus/${uploadId}`;
111
+ }
112
+ async createJobFromFile(filePath, options = {}) {
113
+ const filename = path.basename(filePath);
114
+ const fileSize = fs.statSync(filePath).size;
115
+ if (fileSize > LARGE_FILE_THRESHOLD) {
116
+ console.log(`File is ${(fileSize / 1024 / 1024).toFixed(1)}MB \u2014 using resumable TUS upload...`);
117
+ const uploadedUrl = await this.tusUpload(filePath, filename);
118
+ return this.createJobFromUrl(uploadedUrl, options);
119
+ }
120
+ const form = new FormData();
121
+ const fileBlob = new Blob([fs.readFileSync(filePath)]);
122
+ form.append("image", fileBlob, filename);
123
+ if (options.model) form.append("model", options.model);
124
+ if (options.scale) form.append("scale", String(options.scale));
125
+ return this.request("POST", "/jobs", form);
126
+ }
127
+ async createJobFromUrl(imageUrl, options = {}) {
128
+ const body = {
129
+ image_url: imageUrl,
130
+ ...options.model && { model: options.model },
131
+ ...options.scale && { scale: options.scale }
132
+ };
133
+ return this.request("POST", "/jobs", body);
134
+ }
135
+ async getJob(id) {
136
+ return this.request("GET", `/jobs/${id}`);
137
+ }
138
+ async listJobs(params = {}) {
139
+ const qs = new URLSearchParams();
140
+ if (params.status) qs.set("status", params.status);
141
+ if (params.model) qs.set("model", params.model);
142
+ if (params.limit) qs.set("limit", String(params.limit));
143
+ if (params.cursor) qs.set("cursor", params.cursor);
144
+ if (params.before) qs.set("before", params.before);
145
+ if (params.after) qs.set("after", params.after);
146
+ const query = qs.toString() ? `?${qs}` : "";
147
+ return this.request("GET", `/jobs${query}`);
148
+ }
149
+ async waitForJob(id, { pollInterval = 2e3, timeout = 3e5 } = {}) {
150
+ const start = Date.now();
151
+ while (true) {
152
+ const job = await this.getJob(id);
153
+ if (job.status === "completed" || job.status === "failed") return job;
154
+ if (Date.now() - start > timeout) throw new Error(`Timeout waiting for job ${id}`);
155
+ await new Promise((r) => setTimeout(r, pollInterval));
156
+ }
157
+ }
158
+ async downloadResult(job, outputPath) {
159
+ if (!job.result_url) throw new Error("Job has no result URL");
160
+ const res = await fetch(job.result_url);
161
+ if (!res.ok) throw new Error(`Failed to download result: HTTP ${res.status}`);
162
+ const buf = Buffer.from(await res.arrayBuffer());
163
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
164
+ fs.writeFileSync(outputPath, buf);
165
+ }
166
+ };
167
+
168
+ // src/models.ts
169
+ var MODELS = [
170
+ {
171
+ id: "wavespeed-ai/real-esrgan",
172
+ name: "Real-ESRGAN",
173
+ description: "Fast image super-resolution with artifact removal. Best value.",
174
+ category: "image-upscale",
175
+ price: "$0.0024/image",
176
+ inputTypes: ["image/*"],
177
+ params: [
178
+ { name: "image", type: "string", required: true, description: "Image URL" }
179
+ ]
180
+ },
181
+ {
182
+ id: "wavespeed-ai/image-upscaler",
183
+ name: "Image Upscaler",
184
+ description: "AI upscaler to 2K/4K/8K with detail preservation.",
185
+ category: "image-upscale",
186
+ price: "$0.01/image",
187
+ inputTypes: ["image/*"],
188
+ params: [
189
+ { name: "image", type: "string", required: true, description: "Image URL" },
190
+ { name: "target_resolution", type: "string", required: false, default: "4k", options: ["2k", "4k", "8k"], description: "Target output resolution" },
191
+ { name: "output_format", type: "string", required: false, default: "jpeg", options: ["jpeg", "png", "webp"], description: "Output format" }
192
+ ]
193
+ },
194
+ {
195
+ id: "wavespeed-ai/ultimate-image-upscaler",
196
+ name: "Ultimate Image Upscaler",
197
+ description: "Most advanced AI enhancer. Reimagines fine detail at 2K/4K/8K.",
198
+ category: "image-upscale",
199
+ price: "$0.01/image",
200
+ inputTypes: ["image/*"],
201
+ params: [
202
+ { name: "image", type: "string", required: true, description: "Image URL" },
203
+ { name: "target_resolution", type: "string", required: false, default: "4k", options: ["2k", "4k", "8k"], description: "Target output resolution" },
204
+ { name: "output_format", type: "string", required: false, default: "jpeg", options: ["jpeg", "png", "webp"], description: "Output format" }
205
+ ]
206
+ },
207
+ {
208
+ id: "wavespeed-ai/seedvr2/image",
209
+ name: "SeedVR2 Image",
210
+ description: "ByteDance SeedVR2 architecture for sharp, detailed upscaling.",
211
+ category: "image-upscale",
212
+ price: "$0.01/image",
213
+ inputTypes: ["image/*"],
214
+ params: [
215
+ { name: "image", type: "string", required: true, description: "Image URL" },
216
+ { name: "target_resolution", type: "string", required: false, default: "4k", options: ["2k", "4k", "8k"], description: "Target output resolution" },
217
+ { name: "output_format", type: "string", required: false, default: "jpeg", options: ["jpeg", "png", "webp"], description: "Output format" }
218
+ ]
219
+ },
220
+ {
221
+ id: "bria/increase-resolution",
222
+ name: "Bria Increase Resolution",
223
+ description: "Preservation-first 2x/4x upscale. No content drift.",
224
+ category: "image-upscale",
225
+ price: "$0.04/image",
226
+ inputTypes: ["image/*"],
227
+ params: [
228
+ { name: "image", type: "string", required: true, description: "Image URL. Max output 8192x8192" },
229
+ { name: "desired_increase", type: "integer", required: false, default: 2, options: [2, 4], description: "Resolution multiplier" }
230
+ ]
231
+ },
232
+ {
233
+ id: "clarity-ai/crystal-upscaler",
234
+ name: "Crystal Upscaler",
235
+ description: "Upscale to target megapixels with creativity control.",
236
+ category: "image-upscale",
237
+ price: "Pay per use",
238
+ inputTypes: ["image/*"],
239
+ params: [
240
+ { name: "image", type: "string", required: true, description: "Image URL" },
241
+ { name: "target_megapixels", type: "number", required: false, default: 2, range: "1-200", description: "Target size in megapixels" },
242
+ { name: "creativity", type: "number", required: false, default: 0, range: "0-10", description: "Quality improvement strength" }
243
+ ]
244
+ },
245
+ {
246
+ id: "recraft-ai/recraft-crisp-upscale",
247
+ name: "Recraft Crisp Upscale",
248
+ description: "Enhances textures and facial features. Ideal for portraits.",
249
+ category: "image-enhance",
250
+ price: "Pay per use",
251
+ inputTypes: ["image/*"],
252
+ params: [
253
+ { name: "image", type: "string", required: true, description: "Image URL or base64" }
254
+ ]
255
+ },
256
+ {
257
+ id: "recraft-ai/recraft-creative-upscale",
258
+ name: "Recraft Creative Upscale",
259
+ description: "Generative enhancement adding depth and polish to complex elements.",
260
+ category: "image-enhance",
261
+ price: "$0.25/image",
262
+ inputTypes: ["image/*"],
263
+ params: [
264
+ { name: "image", type: "string", required: true, description: "Image URL or base64" }
265
+ ]
266
+ },
267
+ {
268
+ id: "wavespeed-ai/phota/enhance",
269
+ name: "Phota Enhance",
270
+ description: "Batch enhancement up to 4 images per run with optional 4K output.",
271
+ category: "image-enhance",
272
+ price: "$0.09/image",
273
+ inputTypes: ["image/*"],
274
+ params: [
275
+ { name: "image", type: "string", required: true, description: "Image URL or base64 data URI" },
276
+ { name: "num_images", type: "integer", required: false, default: 1, range: "1-4", description: "Enhanced variations to generate" },
277
+ { name: "output_format", type: "string", required: false, default: "jpeg", options: ["jpeg", "png", "webp"], description: "Output format" }
278
+ ]
279
+ },
280
+ {
281
+ id: "wavespeed-ai/z-image-turbo/image-to-image",
282
+ name: "Z-Image Turbo",
283
+ description: "Fast enhance with strength control. Low strength = subtle upscale.",
284
+ category: "image-enhance",
285
+ price: "$0.01/image",
286
+ inputTypes: ["image/*"],
287
+ params: [
288
+ { name: "image", type: "string", required: true, description: "Reference image URL" },
289
+ { name: "prompt", type: "string", required: true, description: "Enhancement prompt", default: "enhance image quality, sharp details" },
290
+ { name: "strength", type: "number", required: false, default: 0.2, range: "0.00-1.00", description: "0-0.3 subtle enhance, 0.3-0.6 moderate, 0.6+ creative" },
291
+ { name: "size", type: "string", required: false, default: "1024*1024", description: "Output size (width*height)" },
292
+ { name: "seed", type: "integer", required: false, default: -1, range: "-1-2147483647", description: "Random seed. -1 = random" },
293
+ { name: "output_format", type: "string", required: false, default: "jpeg", options: ["jpeg", "png", "webp"], description: "Output format" }
294
+ ]
295
+ },
296
+ {
297
+ id: "wavespeed-ai/video-upscaler",
298
+ name: "Video Upscaler",
299
+ description: "Fast AI video upscaling to 720p-4K. Best value for video.",
300
+ category: "video-upscale",
301
+ price: "$0.005-0.02/sec",
302
+ inputTypes: ["video/*"],
303
+ params: [
304
+ { name: "video", type: "string", required: true, description: "Video URL. Max 10 minutes" },
305
+ { name: "target_resolution", type: "string", required: false, default: "1080p", options: ["720p", "1080p", "2k", "4k"], description: "Target resolution" }
306
+ ]
307
+ },
308
+ {
309
+ id: "wavespeed-ai/video-upscaler-pro",
310
+ name: "Video Upscaler Pro",
311
+ description: "Motion-aware processing with artifact cleanup for pro results.",
312
+ category: "video-upscale",
313
+ price: "$0.03-0.05/sec",
314
+ inputTypes: ["video/*"],
315
+ params: [
316
+ { name: "video", type: "string", required: true, description: "Video URL. Max 10 minutes" },
317
+ { name: "target_resolution", type: "string", required: false, default: "1080p", options: ["720p", "1080p", "2k", "4k"], description: "Target resolution" }
318
+ ]
319
+ },
320
+ {
321
+ id: "wavespeed-ai/ultimate-video-upscaler",
322
+ name: "Ultimate Video Upscaler",
323
+ description: "Deep learning detail reconstruction for highest quality 4K video.",
324
+ category: "video-upscale",
325
+ price: "$0.02-0.08/sec",
326
+ inputTypes: ["video/*"],
327
+ params: [
328
+ { name: "video", type: "string", required: true, description: "Video URL. Max 10 minutes" },
329
+ { name: "target_resolution", type: "string", required: false, default: "1080p", options: ["720p", "1080p", "2k", "4k"], description: "Target resolution" }
330
+ ]
331
+ },
332
+ {
333
+ id: "wavespeed-ai/seedvr2/video",
334
+ name: "SeedVR2 Video",
335
+ description: "16B param ByteDance model. Highest fidelity with frame consistency.",
336
+ category: "video-upscale",
337
+ price: "$0.02-0.05/sec",
338
+ inputTypes: ["video/*"],
339
+ params: [
340
+ { name: "video", type: "string", required: true, description: "Video URL. Max 10 minutes" },
341
+ { name: "target_resolution", type: "string", required: false, default: "1080p", options: ["720p", "1080p", "2k", "4k"], description: "Target resolution" }
342
+ ]
343
+ },
344
+ {
345
+ id: "bytedance/video-upscaler",
346
+ name: "ByteDance Video Upscaler",
347
+ description: "ByteDance super-resolution recovering fine detail to 4K.",
348
+ category: "video-upscale",
349
+ price: "$0.007-0.029/sec",
350
+ inputTypes: ["video/*"],
351
+ params: [
352
+ { name: "video", type: "string", required: true, description: "Video URL" },
353
+ { name: "target_resolution", type: "string", required: false, default: "1080p", options: ["1080p", "2k", "4k"], description: "Target resolution" }
354
+ ]
355
+ },
356
+ {
357
+ id: "bria/fibo/video-upscaler",
358
+ name: "Bria Video Upscaler",
359
+ description: "Temporal consistency with multiple output codec options.",
360
+ category: "video-upscale",
361
+ price: "$0.14/sec",
362
+ inputTypes: ["video/*"],
363
+ params: [
364
+ { name: "video", type: "string", required: true, description: "Video URL" },
365
+ { name: "target_resolution", type: "string", required: false, default: "2k", options: ["2k", "4k"], description: "Target resolution" },
366
+ { name: "output_container_and_codec", type: "string", required: false, default: "mp4_h264", options: ["webm_vp9", "mp4_h264", "mp4_h265", "mov_h265", "mov_prores4s", "mkv_h264", "mkv_h265", "mkv_vp9", "gif"], description: "Output container and codec" }
367
+ ]
368
+ },
369
+ {
370
+ id: "runwayml/upscale-v1",
371
+ name: "RunwayML Upscale",
372
+ description: "Simple one-click video upscale to 4K by RunwayML.",
373
+ category: "video-upscale",
374
+ price: "$0.02/sec",
375
+ inputTypes: ["video/*"],
376
+ params: [
377
+ { name: "video", type: "string", required: true, description: "Video URL. Max 10 minutes" }
378
+ ]
379
+ }
380
+ ];
381
+ var IMAGE_MODELS = MODELS.filter((m) => m.category !== "video-upscale");
382
+ var VIDEO_MODELS = MODELS.filter((m) => m.category === "video-upscale");
383
+ var DEFAULT_IMAGE_MODEL = "wavespeed-ai/image-upscaler";
384
+ var DEFAULT_VIDEO_MODEL = "wavespeed-ai/video-upscaler";
385
+
386
+ // src/cli.ts
387
+ var VERSION = "0.1.0";
388
+ function parseArgs(argv) {
389
+ const args = [];
390
+ const flags = {};
391
+ let i = 0;
392
+ while (i < argv.length) {
393
+ const a = argv[i];
394
+ if (a.startsWith("--")) {
395
+ const key = a.slice(2);
396
+ const next = argv[i + 1];
397
+ if (next && !next.startsWith("--")) {
398
+ flags[key] = next;
399
+ i += 2;
400
+ } else {
401
+ flags[key] = true;
402
+ i++;
403
+ }
404
+ } else {
405
+ args.push(a);
406
+ i++;
407
+ }
408
+ }
409
+ return { command: args[0] ?? "", args: args.slice(1), flags };
410
+ }
411
+ function printHelp() {
412
+ console.log(`
413
+ upres-cli v${VERSION} \u2014 AI image & video upscaling
414
+
415
+ USAGE
416
+ upres <command> [options]
417
+
418
+ COMMANDS
419
+ upscale <file|url> Upscale a single image or video
420
+ batch <dir> Upscale all images in a directory
421
+ models List available models
422
+ jobs List recent jobs
423
+ account Show quota and plan info
424
+ version Print version
425
+
426
+ OPTIONS
427
+ --model <id> Model ID (default: wavespeed-ai/image-upscaler)
428
+ --scale <n> Scale factor 2-8 (image only, default: 4)
429
+ --resolution <res> Target resolution: 2k, 4k, 8k, 720p, 1080p (default: 4k)
430
+ --output <path> Output file or directory
431
+ --api-key <key> API key (or set UPRES_API_KEY env var)
432
+ --wait Wait for job to complete (default: true)
433
+ --no-wait Return job ID immediately without polling
434
+ --concurrency <n> Parallel jobs for batch (default: 3)
435
+ --limit <n> Number of jobs to list (default: 20)
436
+ --status <s> Filter jobs by status
437
+ --help Show help
438
+
439
+ EXAMPLES
440
+ upres upscale photo.jpg --model real-esrgan --scale 4
441
+ upres upscale photo.jpg --model wavespeed-ai/image-upscaler --resolution 8k --output out.jpg
442
+ upres batch ./photos/ --model wavespeed-ai/real-esrgan --output ./upscaled/
443
+ upres models
444
+ upres jobs --limit 10 --status completed
445
+ upres account
446
+
447
+ API KEY
448
+ 1. Get a free key at https://upres.ai/account/api-keys
449
+ 2. Export: UPRES_API_KEY=upres_yourkey
450
+ 3. Or save: echo '{"apiKey":"upres_yourkey"}' > ~/.config/upres/config.json
451
+
452
+ PRICING
453
+ Free: 5 ops/month
454
+ Pro: $19/month \u2014 100 ops, HD output, no watermark
455
+ Biz: $49/month \u2014 unlimited + batch API + all models
456
+
457
+ https://upres.ai/pricing
458
+ `);
459
+ }
460
+ function resolveModel(modelArg, filePath) {
461
+ if (modelArg) {
462
+ const found = MODELS.find(
463
+ (m) => m.id === modelArg || m.id.endsWith(`/${modelArg}`) || m.name.toLowerCase() === modelArg.toLowerCase()
464
+ );
465
+ return found?.id ?? modelArg;
466
+ }
467
+ const ext = path2.extname(filePath).toLowerCase();
468
+ const videoExts = [".mp4", ".mov", ".avi", ".mkv", ".webm", ".gif"];
469
+ return videoExts.includes(ext) ? DEFAULT_VIDEO_MODEL : DEFAULT_IMAGE_MODEL;
470
+ }
471
+ function resolveOutputPath(input, outputDir) {
472
+ const ext = path2.extname(input);
473
+ const base = path2.basename(input, ext);
474
+ const outExt = ext || ".jpg";
475
+ if (outputDir) {
476
+ fs2.mkdirSync(outputDir, { recursive: true });
477
+ return path2.join(outputDir, `${base}_upscaled${outExt}`);
478
+ }
479
+ const dir = path2.dirname(input);
480
+ return path2.join(dir, `${base}_upscaled${outExt}`);
481
+ }
482
+ async function cmdUpscale(args, flags) {
483
+ const input = args[0];
484
+ if (!input) {
485
+ console.error("Usage: upres upscale <file|url> [options]");
486
+ process.exit(1);
487
+ }
488
+ const client = new UpresClient({ apiKey: flags["api-key"] });
489
+ const model = resolveModel(flags.model, input);
490
+ const scale = flags.scale ? Number(flags.scale) : 4;
491
+ const resolution = flags.resolution ?? "4k";
492
+ const outputPath = flags.output;
493
+ const noWait = flags["no-wait"] === true;
494
+ const isUrl = input.startsWith("http://") || input.startsWith("https://");
495
+ const isFile = !isUrl && fs2.existsSync(input);
496
+ if (!isUrl && !isFile) {
497
+ console.error(`Error: File not found: ${input}`);
498
+ process.exit(1);
499
+ }
500
+ process.stdout.write(`Submitting job... model=${model}
501
+ `);
502
+ let job = isFile ? await client.createJobFromFile(input, { model, scale }) : await client.createJobFromUrl(input, { model, scale });
503
+ console.log(`Job created: ${job.id} (status: ${job.status})`);
504
+ if (noWait) {
505
+ console.log(`Run "upres jobs" to check status.`);
506
+ return;
507
+ }
508
+ process.stdout.write("Waiting for result");
509
+ const interval = setInterval(() => process.stdout.write("."), 1500);
510
+ try {
511
+ job = await client.waitForJob(job.id);
512
+ } finally {
513
+ clearInterval(interval);
514
+ process.stdout.write("\n");
515
+ }
516
+ if (job.status === "failed") {
517
+ console.error(`Job failed: ${job.error ?? "Unknown error"}`);
518
+ process.exit(1);
519
+ }
520
+ const out = outputPath ?? (isFile ? resolveOutputPath(input, void 0) : `output_${job.id.slice(0, 8)}.jpg`);
521
+ process.stdout.write(`Downloading to ${out}...`);
522
+ await client.downloadResult(job, out);
523
+ console.log(" done.");
524
+ console.log(`
525
+ Result: ${out}`);
526
+ console.log(`Original URL: ${job.result_url}`);
527
+ }
528
+ async function cmdBatch(args, flags) {
529
+ const dir = args[0];
530
+ if (!dir || !fs2.existsSync(dir)) {
531
+ console.error("Usage: upres batch <directory> [options]");
532
+ process.exit(1);
533
+ }
534
+ const imageExts = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".webp", ".tiff", ".tif"]);
535
+ const files = fs2.readdirSync(dir).filter((f) => imageExts.has(path2.extname(f).toLowerCase())).map((f) => path2.join(dir, f));
536
+ if (files.length === 0) {
537
+ console.error(`No images found in ${dir}`);
538
+ process.exit(1);
539
+ }
540
+ const outputDir = flags.output ?? path2.join(dir, "upscaled");
541
+ const model = resolveModel(flags.model, files[0]);
542
+ const scale = flags.scale ? Number(flags.scale) : 4;
543
+ const concurrency = flags.concurrency ? Number(flags.concurrency) : 3;
544
+ console.log(`Batch upscaling ${files.length} images with ${model} (concurrency: ${concurrency})`);
545
+ const client = new UpresClient({ apiKey: flags["api-key"] });
546
+ let done = 0;
547
+ let failed = 0;
548
+ async function processFile(filePath) {
549
+ const filename = path2.basename(filePath);
550
+ try {
551
+ const job = await client.createJobFromFile(filePath, { model, scale });
552
+ const completed = await client.waitForJob(job.id);
553
+ if (completed.status === "failed") {
554
+ console.error(` FAILED ${filename}: ${completed.error}`);
555
+ failed++;
556
+ return;
557
+ }
558
+ const outPath = resolveOutputPath(filePath, outputDir);
559
+ await client.downloadResult(completed, outPath);
560
+ done++;
561
+ console.log(` [${done}/${files.length}] ${filename} \u2192 ${path2.basename(outPath)}`);
562
+ } catch (e) {
563
+ console.error(` ERROR ${filename}: ${e.message}`);
564
+ failed++;
565
+ }
566
+ }
567
+ for (let i = 0; i < files.length; i += concurrency) {
568
+ const chunk = files.slice(i, i + concurrency);
569
+ await Promise.all(chunk.map(processFile));
570
+ }
571
+ console.log(`
572
+ Done: ${done} succeeded, ${failed} failed. Output: ${outputDir}`);
573
+ }
574
+ function cmdModels() {
575
+ const categories = ["image-upscale", "image-enhance", "video-upscale"];
576
+ for (const cat of categories) {
577
+ const label = { "image-upscale": "Image Upscale", "image-enhance": "Image Enhance", "video-upscale": "Video Upscale" }[cat];
578
+ console.log(`
579
+ ${label}`);
580
+ console.log("\u2500".repeat(60));
581
+ for (const m of MODELS.filter((x) => x.category === cat)) {
582
+ console.log(` ${m.id.padEnd(44)} ${m.price}`);
583
+ console.log(` ${"".padEnd(44)} ${m.description}`);
584
+ }
585
+ }
586
+ console.log("\n Full model details: https://upres.ai/models");
587
+ }
588
+ async function cmdJobs(flags) {
589
+ const client = new UpresClient({ apiKey: flags["api-key"] });
590
+ const result = await client.listJobs({
591
+ limit: flags.limit ? Number(flags.limit) : 20,
592
+ status: flags.status
593
+ });
594
+ if (result.data.length === 0) {
595
+ console.log("No jobs found.");
596
+ return;
597
+ }
598
+ console.log(`
599
+ ${"ID".padEnd(38)} ${"Status".padEnd(12)} ${"Model".padEnd(35)} Created`);
600
+ console.log("\u2500".repeat(110));
601
+ for (const job of result.data) {
602
+ const created = new Date(job.created_at).toLocaleString();
603
+ console.log(
604
+ `${job.id.padEnd(38)} ${job.status.padEnd(12)} ${job.model.padEnd(35)} ${created}`
605
+ );
606
+ }
607
+ if (result.has_more) console.log(`
608
+ More results available (cursor: ${result.next_cursor})`);
609
+ }
610
+ async function cmdAccount(flags) {
611
+ const client = new UpresClient({ apiKey: flags["api-key"] });
612
+ try {
613
+ const result = await client.listJobs({ limit: 100 });
614
+ const total = result.data.length;
615
+ const completed = result.data.filter((j) => j.status === "completed").length;
616
+ console.log(`
617
+ Account info (based on recent jobs)`);
618
+ console.log(` Recent jobs: ${total}`);
619
+ console.log(` Completed: ${completed}`);
620
+ console.log(` API key env: ${process.env.UPRES_API_KEY ? "set (UPRES_API_KEY)" : "not set"}`);
621
+ console.log(`
622
+ Manage your plan: https://upres.ai/pricing`);
623
+ console.log(` API keys: https://upres.ai/account/api-keys`);
624
+ } catch (e) {
625
+ console.error(e.message);
626
+ }
627
+ }
628
+ async function main() {
629
+ const argv = process.argv.slice(2);
630
+ const { command, args, flags } = parseArgs(argv);
631
+ if (flags.help || flags.h || !command) {
632
+ printHelp();
633
+ process.exit(0);
634
+ }
635
+ if (command === "version" || command === "--version" || command === "-v") {
636
+ console.log(`upres-cli v${VERSION}`);
637
+ process.exit(0);
638
+ }
639
+ switch (command) {
640
+ case "upscale":
641
+ await cmdUpscale(args, flags);
642
+ break;
643
+ case "batch":
644
+ await cmdBatch(args, flags);
645
+ break;
646
+ case "models":
647
+ cmdModels();
648
+ break;
649
+ case "jobs":
650
+ await cmdJobs(flags);
651
+ break;
652
+ case "account":
653
+ await cmdAccount(flags);
654
+ break;
655
+ default:
656
+ console.error(`Unknown command: ${command}
657
+ Run "upres --help" for usage.`);
658
+ process.exit(1);
659
+ }
660
+ }
661
+ main().catch((e) => {
662
+ console.error(`Fatal error: ${e.message}`);
663
+ process.exit(1);
664
+ });
665
+ //# sourceMappingURL=cli.js.map