@genobank/biofs 1.5.2 → 1.6.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/index.js CHANGED
@@ -1,5 +1,31 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+
4
+ // ===== LOAD ENVIRONMENT VARIABLES FROM .ENV FILES =====
5
+ // This runs BEFORE any other code to ensure S3 credentials are available
6
+ const dotenv = require('dotenv');
7
+ const path = require('path');
8
+ const fs = require('fs');
9
+
10
+ // Try loading .env from multiple locations (in order of priority)
11
+ const possibleEnvPaths = [
12
+ path.join(process.cwd(), '.env'), // Current directory
13
+ path.join(__dirname, '..', '.env'), // Parent directory
14
+ path.join(__dirname, '..', '..', '.env'), // Two levels up
15
+ path.join(require('os').homedir(), '.biofs', '.env') // User home directory
16
+ ];
17
+
18
+ for (const envPath of possibleEnvPaths) {
19
+ if (fs.existsSync(envPath)) {
20
+ dotenv.config({ path: envPath });
21
+ if (process.env.DEBUG === '1') {
22
+ console.log(`[DEBUG] Loaded .env from: ${envPath}`);
23
+ }
24
+ break; // Use first found .env
25
+ }
26
+ }
27
+ // ===== END ENVIRONMENT LOADING =====
28
+
3
29
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
30
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
31
  };
@@ -30,8 +56,8 @@ const program = new commander_1.Command();
30
56
  // Set up the CLI
31
57
  program
32
58
  .name('biofs')
33
- .description('BioFS by GenoBank.io - BioNFT-Gated S3 CLI for genomic data')
34
- .version('1.5.2')
59
+ .description('BioFS by GenoBank.io - BioNFT-Gated S3 CLI for genomic data and medical videos')
60
+ .version('1.6.0')
35
61
  .option('--debug', 'Enable debug output')
36
62
  .hook('preAction', (thisCommand) => {
37
63
  // Set global debug flag if --debug is passed
@@ -370,8 +396,9 @@ program
370
396
  // Show welcome message if no command
371
397
  if (process.argv.length === 2) {
372
398
  console.log(chalk_1.default.cyan('\n╔════════════════════════════════════╗'));
373
- console.log(chalk_1.default.cyan('║ BioFS CLI v1.5.2 ║'));
399
+ console.log(chalk_1.default.cyan('║ BioFS CLI v1.6.0 ║'));
374
400
  console.log(chalk_1.default.cyan('║ BioNFT-Gated S3 CLI ║'));
401
+ console.log(chalk_1.default.cyan('║ + Medical Video Support ║'));
375
402
  console.log(chalk_1.default.cyan('╚════════════════════════════════════╝\n'));
376
403
  console.log('Available commands:');
377
404
  console.log(` ${chalk_1.default.green('login')} - Authenticate with Web3 wallet`);
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const commander_1 = require("commander");
8
+ const chalk_1 = __importDefault(require("chalk"));
9
+ const login_1 = require("./commands/login");
10
+ const logout_1 = require("./commands/logout");
11
+ const whoami_1 = require("./commands/whoami");
12
+ const files_1 = require("./commands/files");
13
+ const download_with_consent_1 = require("./commands/download-with-consent");
14
+ const upload_1 = require("./commands/upload");
15
+ const mount_1 = require("./commands/mount");
16
+ const tokenize_1 = require("./commands/tokenize");
17
+ const request_1 = require("./commands/access/request");
18
+ const grant_1 = require("./commands/access/grant");
19
+ const revoke_1 = require("./commands/access/revoke");
20
+ const list_1 = require("./commands/access/list");
21
+ const check_1 = require("./commands/access/check");
22
+ const revoke_consent_1 = require("./commands/access/revoke-consent");
23
+ const create_1 = require("./commands/job/create");
24
+ const status_1 = require("./commands/job/status");
25
+ const results_1 = require("./commands/job/results");
26
+ const list_2 = require("./commands/job/list");
27
+ const pipelines_1 = require("./commands/job/pipelines");
28
+ const logger_1 = require("./lib/utils/logger");
29
+ const program = new commander_1.Command();
30
+ // Set up the CLI
31
+ program
32
+ .name('biofs')
33
+ .description('BioFS by GenoBank.io - BioNFT-Gated S3 CLI for genomic data')
34
+ .version('1.5.2')
35
+ .option('--debug', 'Enable debug output')
36
+ .hook('preAction', (thisCommand) => {
37
+ // Set global debug flag if --debug is passed
38
+ const opts = thisCommand.opts();
39
+ if (opts.debug) {
40
+ process.env.DEBUG = '1';
41
+ }
42
+ });
43
+ // Login command
44
+ program
45
+ .command('login')
46
+ .description('Authenticate with GenoBank.io using Web3 signature')
47
+ .option('--port <number>', 'Callback server port', parseInt)
48
+ .option('--no-browser', "Don't auto-open browser")
49
+ .option('--timeout <seconds>', 'Auth timeout in seconds', parseInt)
50
+ .action(async (options) => {
51
+ try {
52
+ await (0, login_1.loginCommand)(options);
53
+ }
54
+ catch (error) {
55
+ logger_1.Logger.error(`Login failed: ${error}`);
56
+ process.exit(1);
57
+ }
58
+ });
59
+ // Logout command
60
+ program
61
+ .command('logout')
62
+ .description('Clear stored credentials')
63
+ .action(async () => {
64
+ try {
65
+ await (0, logout_1.logoutCommand)();
66
+ }
67
+ catch (error) {
68
+ logger_1.Logger.error(`Logout failed: ${error}`);
69
+ process.exit(1);
70
+ }
71
+ });
72
+ // Whoami command
73
+ program
74
+ .command('whoami')
75
+ .description('Show current authenticated wallet')
76
+ .option('--json', 'Output as JSON')
77
+ .option('--verify', 'Verify signature validity')
78
+ .option('--check <wallet>', 'Check against specific wallet address (e.g., Dra. Claudia: 0xb3c3a584491b8ca4df45116a1e250098a0d6192d)')
79
+ .action(async (options) => {
80
+ try {
81
+ await (0, whoami_1.whoamiCommand)(options);
82
+ }
83
+ catch (error) {
84
+ logger_1.Logger.error(`Error: ${error}`);
85
+ process.exit(1);
86
+ }
87
+ });
88
+ // Files command
89
+ program
90
+ .command('files')
91
+ .alias('ls')
92
+ .description('List your BioFiles from all sources')
93
+ .option('--filter <type>', 'Filter by file type (vcf, fastq, bam, pdf, etc.)')
94
+ .option('--source <source>', 'Filter by source (s3, ipfs, story)')
95
+ .option('--json', 'Output as JSON')
96
+ .option('--refresh', 'Clear cache and fetch fresh data')
97
+ .option('--verbose', 'Show debug information')
98
+ .action(async (options) => {
99
+ try {
100
+ await (0, files_1.filesCommand)(options);
101
+ }
102
+ catch (error) {
103
+ logger_1.Logger.error(`Error listing files: ${error}`);
104
+ process.exit(1);
105
+ }
106
+ });
107
+ // Download command (with GDPR consent for genomic data)
108
+ program
109
+ .command('download <biocid_or_filename> [destination]')
110
+ .alias('get')
111
+ .description('Download a file (with GDPR consent for genomic data)')
112
+ .option('--output <path>', 'Output file path')
113
+ .option('--stream', 'Stream large files (>100MB)')
114
+ .option('--quiet', 'No progress bar')
115
+ .option('--skip-consent', 'Skip GDPR consent (for automation)')
116
+ .action(async (biocidOrFilename, destination, options) => {
117
+ try {
118
+ await (0, download_with_consent_1.downloadCommandWithConsent)(biocidOrFilename, destination, options);
119
+ }
120
+ catch (error) {
121
+ logger_1.Logger.error(`Download failed: ${error}`);
122
+ process.exit(1);
123
+ }
124
+ });
125
+ // Upload command
126
+ program
127
+ .command('upload <file>')
128
+ .alias('put')
129
+ .description('Upload a file to GenoBank')
130
+ .option('--type <type>', 'File type (vcf, fastq, bam, pdf)')
131
+ .option('--tokenize', 'Mint as NFT after upload')
132
+ .option('--share-with <lab>', 'Share with lab after upload')
133
+ .option('--public', 'Make publicly discoverable')
134
+ .option('--quiet', 'No progress output')
135
+ .action(async (filePath, options) => {
136
+ try {
137
+ await (0, upload_1.uploadCommand)(filePath, options);
138
+ }
139
+ catch (error) {
140
+ logger_1.Logger.error(`Upload failed: ${error}`);
141
+ process.exit(1);
142
+ }
143
+ });
144
+ // Mount command (mount all granted BioFiles with GDPR consent)
145
+ program
146
+ .command('mount <mount_point>')
147
+ .description('Mount all granted BioFiles to local directory (with GDPR consent)')
148
+ .option('--read-only', 'Mount as read-only')
149
+ .option('--quiet', 'Suppress output')
150
+ .option('--skip-consent', 'Skip GDPR consent (for automation)')
151
+ .action(async (mountPoint, options) => {
152
+ try {
153
+ await (0, mount_1.mountCommand)(mountPoint, options);
154
+ }
155
+ catch (error) {
156
+ logger_1.Logger.error(`Mount failed: ${error}`);
157
+ process.exit(1);
158
+ }
159
+ });
160
+ // Tokenize command
161
+ program
162
+ .command('tokenize <file>')
163
+ .description('Tokenize a genomic dataset as BioIP NFT on Story Protocol')
164
+ .option('--title <string>', 'Custom title for the NFT')
165
+ .option('--description <string>', 'Custom description (uses AI if not provided)')
166
+ .option('--license <type>', 'License type: commercial, non-commercial', 'non-commercial')
167
+ .option('--collection <address>', 'Manual collection address override')
168
+ .option('--network <network>', 'Story Protocol network: mainnet, testnet', 'mainnet')
169
+ .option('--no-ai', 'Skip AI classification')
170
+ .option('--dryrun', 'Test validation and preview metadata without tokenizing')
171
+ .option('--quiet', 'No interactive prompts')
172
+ .option('--yes', 'Auto-confirm all prompts')
173
+ .action(async (file, options) => {
174
+ try {
175
+ await (0, tokenize_1.tokenizeCommand)(file, options);
176
+ }
177
+ catch (error) {
178
+ logger_1.Logger.error(`Tokenization failed: ${error}`);
179
+ process.exit(1);
180
+ }
181
+ });
182
+ // Access control commands (v1.2.0)
183
+ const accessCmd = program
184
+ .command('access')
185
+ .description('Manage BioNFT access control and permissions');
186
+ // access request
187
+ accessCmd
188
+ .command('request <biocid_or_ip_id>')
189
+ .description('Request access to a BioNFT asset')
190
+ .option('--message <string>', 'Optional message to asset owner')
191
+ .action(async (biocidOrIpId, options) => {
192
+ try {
193
+ await (0, request_1.accessRequestCommand)(biocidOrIpId, options);
194
+ }
195
+ catch (error) {
196
+ logger_1.Logger.error(`Access request failed: ${error}`);
197
+ process.exit(1);
198
+ }
199
+ });
200
+ // access grant
201
+ accessCmd
202
+ .command('grant <biocid_or_ip_id> <wallet_address>')
203
+ .description('Grant access to a wallet address (owner only)')
204
+ .option('--expires-in <duration>', 'Access expiry duration (e.g., 30d, 90d)')
205
+ .action(async (biocidOrIpId, walletAddress, options) => {
206
+ try {
207
+ await (0, grant_1.accessGrantCommand)(biocidOrIpId, walletAddress, options);
208
+ }
209
+ catch (error) {
210
+ logger_1.Logger.error(`Access grant failed: ${error}`);
211
+ process.exit(1);
212
+ }
213
+ });
214
+ // access revoke
215
+ accessCmd
216
+ .command('revoke <biocid_or_ip_id> <wallet_address>')
217
+ .description('Revoke access from a wallet address (owner only)')
218
+ .option('--yes', 'Skip confirmation prompt')
219
+ .action(async (biocidOrIpId, walletAddress, options) => {
220
+ try {
221
+ await (0, revoke_1.accessRevokeCommand)(biocidOrIpId, walletAddress, options);
222
+ }
223
+ catch (error) {
224
+ logger_1.Logger.error(`Access revocation failed: ${error}`);
225
+ process.exit(1);
226
+ }
227
+ });
228
+ // access list
229
+ accessCmd
230
+ .command('list [biocid_or_ip_id]')
231
+ .description('List permittees for an asset, or assets you can access')
232
+ .option('--mine', 'List assets you have permission to access')
233
+ .option('--status <status>', 'Filter by status: active, pending, revoked')
234
+ .option('--json', 'Output as JSON')
235
+ .action(async (biocidOrIpId, options) => {
236
+ try {
237
+ await (0, list_1.accessListCommand)(biocidOrIpId, options);
238
+ }
239
+ catch (error) {
240
+ logger_1.Logger.error(`List failed: ${error}`);
241
+ process.exit(1);
242
+ }
243
+ });
244
+ // access check
245
+ accessCmd
246
+ .command('check <biocid_or_ip_id>')
247
+ .description('Check your access level to a BioNFT asset')
248
+ .action(async (biocidOrIpId) => {
249
+ try {
250
+ await (0, check_1.accessCheckCommand)(biocidOrIpId);
251
+ }
252
+ catch (error) {
253
+ logger_1.Logger.error(`Access check failed: ${error}`);
254
+ process.exit(1);
255
+ }
256
+ });
257
+ // access revoke-consent (user withdraws their own consent - GDPR)
258
+ accessCmd
259
+ .command('revoke-consent [ip_id]')
260
+ .description('Revoke your consent for genomic data access (GDPR right to withdraw)')
261
+ .option('--all', 'Revoke all consents')
262
+ .option('--force', 'Skip confirmation')
263
+ .action(async (ipId, options) => {
264
+ try {
265
+ await (0, revoke_consent_1.revokeConsentCommand)(ipId, options);
266
+ }
267
+ catch (error) {
268
+ logger_1.Logger.error(`Consent revocation failed: ${error}`);
269
+ process.exit(1);
270
+ }
271
+ });
272
+ // Job management commands (BioOS)
273
+ const jobCmd = program
274
+ .command('job')
275
+ .description('Manage research jobs (BioOS)');
276
+ // job create
277
+ jobCmd
278
+ .command('create <prompt> <file>')
279
+ .description('Create a research job from natural language prompt')
280
+ .option('--pipeline <template>', 'Use predefined pipeline template')
281
+ .option('--json', 'Output as JSON')
282
+ .action(async (prompt, fileRef, options) => {
283
+ try {
284
+ await (0, create_1.jobCreateCommand)(prompt, fileRef, options);
285
+ }
286
+ catch (error) {
287
+ logger_1.Logger.error(`Job creation failed: ${error}`);
288
+ process.exit(1);
289
+ }
290
+ });
291
+ // job status
292
+ jobCmd
293
+ .command('status <job_id>')
294
+ .description('Check job execution status')
295
+ .option('--json', 'Output as JSON')
296
+ .option('--watch', 'Watch mode (refresh every 5 seconds)')
297
+ .action(async (jobId, options) => {
298
+ try {
299
+ await (0, status_1.jobStatusCommand)(jobId, options);
300
+ }
301
+ catch (error) {
302
+ logger_1.Logger.error(`Status check failed: ${error}`);
303
+ process.exit(1);
304
+ }
305
+ });
306
+ // job results
307
+ jobCmd
308
+ .command('results <job_id>')
309
+ .description('Get job results with download URLs')
310
+ .option('--json', 'Output as JSON')
311
+ .option('--step <number>', 'Download specific step only', parseInt)
312
+ .action(async (jobId, options) => {
313
+ try {
314
+ await (0, results_1.jobResultsCommand)(jobId, options);
315
+ }
316
+ catch (error) {
317
+ logger_1.Logger.error(`Failed to get results: ${error}`);
318
+ process.exit(1);
319
+ }
320
+ });
321
+ // job list
322
+ jobCmd
323
+ .command('list')
324
+ .description('List all your research jobs')
325
+ .option('--json', 'Output as JSON')
326
+ .option('--status <status>', 'Filter by status (pending, running, completed, failed)')
327
+ .option('--limit <number>', 'Limit number of results', parseInt)
328
+ .action(async (options) => {
329
+ try {
330
+ await (0, list_2.jobListCommand)(options);
331
+ }
332
+ catch (error) {
333
+ logger_1.Logger.error(`Failed to list jobs: ${error}`);
334
+ process.exit(1);
335
+ }
336
+ });
337
+ // job pipelines
338
+ jobCmd
339
+ .command('pipelines')
340
+ .alias('templates')
341
+ .description('List available pipeline templates')
342
+ .option('--json', 'Output as JSON')
343
+ .action(async (options) => {
344
+ try {
345
+ await (0, pipelines_1.pipelinesCommand)(options);
346
+ }
347
+ catch (error) {
348
+ logger_1.Logger.error(`Failed to list pipelines: ${error}`);
349
+ process.exit(1);
350
+ }
351
+ });
352
+ // Help command
353
+ program
354
+ .command('help [command]')
355
+ .description('Display help for a command')
356
+ .action((cmd) => {
357
+ if (cmd) {
358
+ const command = program.commands.find(c => c.name() === cmd);
359
+ if (command) {
360
+ command.outputHelp();
361
+ }
362
+ else {
363
+ logger_1.Logger.error(`Unknown command: ${cmd}`);
364
+ }
365
+ }
366
+ else {
367
+ program.outputHelp();
368
+ }
369
+ });
370
+ // Show welcome message if no command
371
+ if (process.argv.length === 2) {
372
+ console.log(chalk_1.default.cyan('\n╔════════════════════════════════════╗'));
373
+ console.log(chalk_1.default.cyan('║ BioFS CLI v1.5.2 ║'));
374
+ console.log(chalk_1.default.cyan('║ BioNFT-Gated S3 CLI ║'));
375
+ console.log(chalk_1.default.cyan('╚════════════════════════════════════╝\n'));
376
+ console.log('Available commands:');
377
+ console.log(` ${chalk_1.default.green('login')} - Authenticate with Web3 wallet`);
378
+ console.log(` ${chalk_1.default.green('logout')} - Clear credentials`);
379
+ console.log(` ${chalk_1.default.green('whoami')} - Show current wallet`);
380
+ console.log(` ${chalk_1.default.green('files')} - List your BioFiles`);
381
+ console.log(` ${chalk_1.default.green('download')} - Download files (GDPR consent)`);
382
+ console.log(` ${chalk_1.default.green('mount')} - Mount all files (GDPR consent)`);
383
+ console.log(` ${chalk_1.default.green('upload')} - Upload files`);
384
+ console.log(` ${chalk_1.default.green('tokenize')} - Tokenize as BioIP NFT`);
385
+ console.log(` ${chalk_1.default.green('access')} - Manage BioNFT access control`);
386
+ console.log(` ${chalk_1.default.green('job')} - Manage research jobs (BioOS)`);
387
+ console.log(` ${chalk_1.default.green('help')} - Show help\n`);
388
+ console.log('Access control subcommands:');
389
+ console.log(` ${chalk_1.default.cyan('access request')} <biocid> - Request access to asset`);
390
+ console.log(` ${chalk_1.default.cyan('access grant')} <biocid> <wallet> - Grant access (owner)`);
391
+ console.log(` ${chalk_1.default.cyan('access revoke')} <biocid> <wallet> - Revoke access (owner)`);
392
+ console.log(` ${chalk_1.default.cyan('access list')} [biocid] - List permittees or permissions`);
393
+ console.log(` ${chalk_1.default.cyan('access check')} <biocid> - Check your access level`);
394
+ console.log(` ${chalk_1.default.cyan('access revoke-consent')} [ip_id] - Revoke YOUR consent (GDPR)\n`);
395
+ console.log('Research job subcommands (BioOS):');
396
+ console.log(` ${chalk_1.default.cyan('job create')} "<prompt>" <file> - Create research job`);
397
+ console.log(` ${chalk_1.default.cyan('job status')} <job_id> - Check job status`);
398
+ console.log(` ${chalk_1.default.cyan('job results')} <job_id> - Get job results`);
399
+ console.log(` ${chalk_1.default.cyan('job list')} - List all jobs`);
400
+ console.log(` ${chalk_1.default.cyan('job pipelines')} - List pipeline templates\n`);
401
+ console.log(`Run ${chalk_1.default.cyan('biofs help <command>')} for detailed usage.\n`);
402
+ }
403
+ else {
404
+ // Parse command line arguments
405
+ program.parse(process.argv);
406
+ }
407
+ // Handle uncaught errors
408
+ process.on('unhandledRejection', (error) => {
409
+ logger_1.Logger.error(`Unexpected error: ${error}`);
410
+ process.exit(1);
411
+ });
412
+ process.on('SIGINT', () => {
413
+ console.log('\n\nInterrupted. Goodbye!');
414
+ // Give inquirer time to clean up before exiting
415
+ setTimeout(() => process.exit(0), 100);
416
+ });
417
+ //# sourceMappingURL=index.js.map
@@ -41,7 +41,6 @@ export declare const API_CONFIG: {
41
41
  bioip: string;
42
42
  timeout: number;
43
43
  };
44
- export declare const GEMINI_API_KEY: string | undefined;
45
44
  export declare const FILE_TYPES: {
46
45
  vcf: {
47
46
  ext: string[];
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.FILE_TYPES = exports.GEMINI_API_KEY = exports.API_CONFIG = exports.STORY_NETWORKS = exports.CONFIG = void 0;
6
+ exports.FILE_TYPES = exports.API_CONFIG = exports.STORY_NETWORKS = exports.CONFIG = void 0;
7
7
  const dotenv_1 = __importDefault(require("dotenv"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  // Load .env from CLI root
@@ -59,8 +59,6 @@ exports.API_CONFIG = {
59
59
  bioip: '/api_bioip',
60
60
  timeout: 300000 // 5 minutes for large file uploads
61
61
  };
62
- // Gemini AI Configuration
63
- exports.GEMINI_API_KEY = process.env.GEMINI_API_KEY;
64
62
  exports.FILE_TYPES = {
65
63
  vcf: { ext: ['.vcf', '.vcf.gz'], desc: 'Variant Call Format' },
66
64
  fastq: { ext: ['.fastq', '.fastq.gz', '.fq', '.fq.gz'], desc: 'FASTQ sequence' },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@genobank/biofs",
3
- "version": "1.5.2",
4
- "description": "BioFS - GenoBank.io BioNFT-Gated S3 CLI with GDPR Consent for genomic data",
3
+ "version": "1.6.0",
4
+ "description": "BioFS - GenoBank.io BioNFT-Gated S3 CLI with GDPR Consent for genomic data and medical videos (Luma AI, Precigenetics)",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
7
7
  "biofs": "./bin/biofs.js"
@@ -12,7 +12,6 @@
12
12
  "test": "jest"
13
13
  },
14
14
  "dependencies": {
15
- "@google/generative-ai": "^0.24.1",
16
15
  "axios": "^1.6.0",
17
16
  "boxen": "^5.1.2",
18
17
  "chalk": "^4.1.2",
@@ -1,10 +0,0 @@
1
- export interface ClassificationResult {
2
- description: string;
3
- category: string;
4
- suggestedTitle: string;
5
- }
6
- /**
7
- * Classify a genomic dataset using Gemini AI
8
- */
9
- export declare function classifyDataset(filePath: string): Promise<ClassificationResult>;
10
- //# sourceMappingURL=classifier.d.ts.map
@@ -1,155 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.classifyDataset = classifyDataset;
4
- const promises_1 = require("fs/promises");
5
- const path_1 = require("path");
6
- const generative_ai_1 = require("@google/generative-ai");
7
- const constants_1 = require("../config/constants");
8
- // Use environment variable or fallback to hardcoded key
9
- const API_KEY = constants_1.GEMINI_API_KEY || 'AIzaSyCuPPjSPkHTbu2YBoyZjUB-o-xCnhCNaac';
10
- /**
11
- * Classify a genomic dataset using Gemini AI
12
- */
13
- async function classifyDataset(filePath) {
14
- try {
15
- // Initialize Gemini
16
- const genAI = new generative_ai_1.GoogleGenerativeAI(API_KEY);
17
- const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
18
- // Read file sample (first 100 lines or 10KB, whichever is smaller)
19
- const fileContent = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
20
- const lines = fileContent.split('\n');
21
- const sampleLines = lines.slice(0, 100);
22
- const sampleContent = sampleLines.join('\n').substring(0, 10000);
23
- // Get file info
24
- const fileName = (0, path_1.basename)(filePath);
25
- const fileExt = (0, path_1.extname)(filePath);
26
- // Create prompt
27
- const prompt = `You are a genomic data expert. Analyze this genomic dataset and provide:
28
- 1. A concise 2-3 sentence description suitable for NFT metadata
29
- 2. The category (must be one of: vcf, genomic, gwas, sequence, alignment, annotation, microarray, snp, dtc, medical_imaging, medical)
30
- 3. A suggested title (max 50 characters)
31
-
32
- File: ${fileName}
33
- File type: ${fileExt}
34
- Sample content (first 100 lines):
35
- ${sampleContent}
36
-
37
- IMPORTANT: Respond ONLY in valid JSON format with no additional text or markdown:
38
- {
39
- "description": "...",
40
- "category": "...",
41
- "suggestedTitle": "..."
42
- }`;
43
- // Get AI response
44
- const result = await model.generateContent(prompt);
45
- const response = await result.response;
46
- const text = response.text();
47
- // Parse JSON response
48
- // Clean the response (remove markdown if present)
49
- const cleanedText = text.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim();
50
- try {
51
- const parsed = JSON.parse(cleanedText);
52
- return {
53
- description: parsed.description || generateDefaultDescription(fileName, fileExt),
54
- category: validateCategory(parsed.category) || detectCategoryFromExtension(fileExt),
55
- suggestedTitle: parsed.suggestedTitle || generateDefaultTitle(fileName)
56
- };
57
- }
58
- catch (parseError) {
59
- // If JSON parsing fails, use defaults
60
- return generateDefaultClassification(fileName, fileExt);
61
- }
62
- }
63
- catch (error) {
64
- // If AI fails, use default classification
65
- return generateDefaultClassification((0, path_1.basename)(filePath), (0, path_1.extname)(filePath));
66
- }
67
- }
68
- /**
69
- * Generate default classification if AI fails
70
- */
71
- function generateDefaultClassification(fileName, fileExt) {
72
- return {
73
- description: generateDefaultDescription(fileName, fileExt),
74
- category: detectCategoryFromExtension(fileExt),
75
- suggestedTitle: generateDefaultTitle(fileName)
76
- };
77
- }
78
- /**
79
- * Generate default description based on file type
80
- */
81
- function generateDefaultDescription(fileName, fileExt) {
82
- const extDescriptions = {
83
- '.vcf': 'Variant Call Format file containing genomic variant information from sequencing analysis.',
84
- '.bam': 'Binary Alignment Map file containing aligned sequencing reads mapped to a reference genome.',
85
- '.sam': 'Sequence Alignment Map file containing aligned sequencing reads in text format.',
86
- '.fastq': 'Raw sequencing reads with quality scores from high-throughput sequencing.',
87
- '.fasta': 'Nucleotide or protein sequences in FASTA format.',
88
- '.txt': 'Direct-to-consumer genetic testing results containing SNP genotype data.',
89
- '.csv': 'Genomic data in comma-separated values format, possibly GWAS or variant annotations.',
90
- '.bed': 'Browser Extensible Data format defining genomic regions and annotations.',
91
- '.gff': 'General Feature Format file containing genomic features and annotations.',
92
- '.dcm': 'DICOM medical imaging file containing radiological or medical scan data.'
93
- };
94
- const ext = fileExt.toLowerCase();
95
- return extDescriptions[ext] || `Genomic dataset file: ${fileName}. Contains biological sequence or variant data for analysis.`;
96
- }
97
- /**
98
- * Detect category from file extension
99
- */
100
- function detectCategoryFromExtension(fileExt) {
101
- const extCategories = {
102
- '.vcf': 'vcf',
103
- '.vcf.gz': 'vcf',
104
- '.bam': 'alignment',
105
- '.sam': 'alignment',
106
- '.fastq': 'sequence',
107
- '.fq': 'sequence',
108
- '.fastq.gz': 'sequence',
109
- '.fasta': 'sequence',
110
- '.fa': 'sequence',
111
- '.txt': 'dtc',
112
- '.csv': 'gwas',
113
- '.tsv': 'gwas',
114
- '.bed': 'annotation',
115
- '.gff': 'annotation',
116
- '.gtf': 'annotation',
117
- '.dcm': 'medical_imaging',
118
- '.dicom': 'medical_imaging'
119
- };
120
- const ext = fileExt.toLowerCase();
121
- return extCategories[ext] || 'genomic';
122
- }
123
- /**
124
- * Generate default title from filename
125
- */
126
- function generateDefaultTitle(fileName) {
127
- // Remove extension
128
- let title = fileName.replace(/\.[^/.]+$/, '');
129
- // Replace underscores and dashes with spaces
130
- title = title.replace(/[_-]/g, ' ');
131
- // Capitalize words
132
- title = title.split(' ')
133
- .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
134
- .join(' ');
135
- // Limit length
136
- if (title.length > 50) {
137
- title = title.substring(0, 47) + '...';
138
- }
139
- return title;
140
- }
141
- /**
142
- * Validate category returned by AI
143
- */
144
- function validateCategory(category) {
145
- if (!category)
146
- return null;
147
- const validCategories = [
148
- 'vcf', 'genomic', 'gwas', 'sequence', 'alignment',
149
- 'annotation', 'microarray', 'snp', 'dtc',
150
- 'medical_imaging', 'medical'
151
- ];
152
- const normalized = category.toLowerCase().trim();
153
- return validCategories.includes(normalized) ? normalized : null;
154
- }
155
- //# sourceMappingURL=classifier.js.map