### Install Reality Defender SDK Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Install the SDK using either yarn or npm. ```bash # Using yarn yarn add @realitydefender/realitydefender # Using npm npm install @realitydefender/realitydefender ``` -------------------------------- ### Set API Key and Run Examples Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Configure your API key as an environment variable and execute the example scripts using yarn. ```bash # Navigate to the typescript directory cd examples # Install dependencies yarn install export REALITY_DEFENDER_API_KEY='' yarn example:basic yarn example:getresults yarn example:social_media ``` -------------------------------- ### Add Sample File Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Copy a sample media file into the examples directory for testing purposes. ```bash # Copy an image file to the examples directory cp /path/to/your/image.jpg examples/sample-image.jpg ``` -------------------------------- ### Quick Start Media Detection Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Use the `detect` method for a single-step upload and analysis. Initialize the SDK with your API key. This method handles both uploading the file and processing the analysis results. ```typescript import { RealityDefender } from '@realitydefender/realitydefender'; // Initialize the SDK with your API key const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function detectMedia() { try { // Upload and analyze in one step const result = await realityDefender.detect({ filePath: '/path/to/your/file.jpg', }); // Process the results console.log(`Status: ${result.status}`); console.log(`Score: ${result.score}`); // Score is a value between 0 and 1 return result; } catch (error: any) { console.error(`Error: ${error.message} (${error.code})`); throw error; } } // Call the function detectMedia() .then(result => console.log('Detection completed successfully')) .catch(error => console.error('Detection failed')); ``` -------------------------------- ### Event-Driven Polling for Analysis Results Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Starts asynchronous polling for results with event-based callbacks, suitable for long-running operations. Emits 'result' or 'error' events. Requires uploading a file first and registering event handlers before starting polling. ```typescript import { RealityDefender, RealityDefenderError, DetectionResult } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function analyzeWithEvents() { // Upload file first const { requestId } = await realityDefender.upload({ filePath: '/path/to/audio.mp3', }); console.log(`Request ID: ${requestId}`); // Register event handlers before starting polling realityDefender.on('result', (result: DetectionResult) => { console.log('Analysis complete!'); console.log(`Status: ${result.status}`); console.log(`Score: ${result.score?.toFixed(2) || 'N/A'}`); result.models.forEach(model => { console.log(` ${model.name}: ${model.status} (${model.score?.toFixed(2) || 'N/A'})`); }); }); realityDefender.on('error', (error: RealityDefenderError) => { console.error(`Error: ${error.message}`); console.error(`Code: ${error.code}`); // Error codes: 'timeout', 'not_found', 'server_error', 'unauthorized' }); // Start polling (non-blocking) realityDefender.pollForResults(requestId, { pollingInterval: 3000, // Check every 3 seconds (default: 5000ms) timeout: 120000, // Timeout after 2 minutes (default: 300000ms) }); console.log('Polling started, waiting for results...'); } analyzeWithEvents(); // Expected output: // Request ID: def456-ghi789 // Polling started, waiting for results... // Analysis complete! // Status: AUTHENTIC // Score: 0.08 // AudioDeepfake: AUTHENTIC (0.05) // VoiceClone: AUTHENTIC (0.11) ``` -------------------------------- ### GET /getResults Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Retrieves a paginated list of all detection results with optional filtering by name and date range. ```APIDOC ## GET /getResults ### Description Retrieves a paginated list of all detection results with optional filtering by name and date range. Useful for dashboards, batch processing, and historical analysis. ### Method GET ### Parameters #### Query Parameters - **pageNumber** (number) - Required - The page index (0-indexed). - **pageSize** (number) - Required - The number of items per page. - **name** (string) - Optional - Filter by media name. - **startDate** (Date) - Optional - Filter by start date. - **endDate** (Date) - Optional - Filter by end date. ### Response #### Success Response (200) - **totalItems** (number) - Total count of items. - **totalPages** (number) - Total number of pages. - **currentPage** (number) - Current page index. - **currentPageItemsCount** (number) - Number of items on the current page. - **items** (array) - List of detection result objects. ``` -------------------------------- ### Get Results Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Retrieves the detection results for a specific request ID. ```APIDOC ## getResult(requestId) ### Description Fetches the detection result for a given request ID. ### Parameters #### Path Parameters - **requestId** (string) - Required - The ID of the request to retrieve ### Response #### Success Response (200) - **status** (string) - Overall status (e.g., "MANIPULATED", "AUTHENTIC") - **score** (number) - Overall confidence score (0-1 range) - **models** (array) - Array of model-specific results ``` -------------------------------- ### List Detection Results with getResults Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Retrieves paginated detection results, supporting filtering by name and date range. Includes examples for basic pagination, filtered queries, and iterating through all pages. ```typescript import { RealityDefender } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: process.env.REALITY_DEFENDER_API_KEY!, }); async function listResults() { // Get first page with 10 results const results = await realityDefender.getResults( 0, // pageNumber (0-indexed) 10 // page size ); console.log(`Total Items: ${results.totalItems}`); console.log(`Total Pages: ${results.totalPages}`); console.log(`Current Page: ${results.currentPage}`); console.log(`Items on Page: ${results.currentPageItemsCount}`); results.items.forEach((item, index) => { console.log(`${index + 1}. Status: ${item.status}, Score: ${item.score}`); }); } async function listFilteredResults() { // Filter by date range (last 7 days) const sevenDaysAgo = new Date(); sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7); const results = await realityDefender.getResults( 0, // pageNumber 20, // page size 'video', // name filter (null to skip) sevenDaysAgo, // startDate (null to skip) new Date() // endDate (null to skip) ); console.log(`Found ${results.totalItems} results from the last 7 days`); results.items.forEach(item => { console.log(` Status: ${item.status}, Score: ${item.score}`); }); } async function paginateThroughAllResults() { const pageSize = 5; let pageNumber = 0; while (true) { const results = await realityDefender.getResults(pageNumber, pageSize); if (results.currentPageItemsCount === 0) break; console.log(`Page ${pageNumber + 1}:`); results.items.forEach((item, i) => { console.log(` ${i + 1}. ${item.status} - ${item.score}`); }); if (pageNumber >= results.totalPages - 1) break; pageNumber++; } } listResults(); ``` -------------------------------- ### Event-Driven Media Detection Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Implement an event-driven approach for long-running operations without blocking the main thread. This involves uploading a file, starting to poll for results, and listening for 'result' and 'error' events. ```typescript import { RealityDefender } from '@realitydefender/realitydefender'; async function detectMedia() { // Initialize the SDK with your API key const realityDefender = new RealityDefender({ apiKey: 'your-api-key' }); // Upload a file for analysis const {requestId} = await realityDefender.upload({ filePath: '/path/to/your/file.jpg', }); //Start polling realityDefender.pollForResults(requestId, { pollingInterval: 3000, timeout: 60000 }); // Event-based approach to get results realityDefender.on('result', (result) => { console.log(`Status: ${result.status}`); console.log(`Score: ${result.score}`); // Score is a value between 0 and 1 // List model results result.models.forEach(model => { console.log(`${model.name}: ${model.status} (${model.score})`); // Model scores are also between 0 and 1 }); }); realityDefender.on('error', (error) => { console.error(`Error: ${error.message} (${error.code})`); }); } // Call the function detectMedia() .then(result => console.log('Waiting for result')) .catch(error => console.error('Detection failed')); ``` -------------------------------- ### GET /getResult Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Retrieves detection results for a previously uploaded media file using the request ID. This method includes automatic polling until analysis is complete. ```APIDOC ## GET /getResult ### Description Retrieves detection results for a previously uploaded media file using the request ID. Automatically polls the API until analysis completes or maximum attempts are reached. ### Method GET ### Parameters #### Path Parameters - **requestId** (string) - Required - The unique identifier for the analysis request. #### Query Parameters - **maxAttempts** (number) - Optional - Maximum polling attempts (default: unlimited). - **pollingInterval** (number) - Optional - Poll interval in milliseconds (default: 5000). ### Response #### Success Response (200) - **requestId** (string) - The request ID. - **status** (string) - The status of the analysis. - **score** (number) - The overall detection score. - **models** (array) - List of individual model results including name, status, and score. ``` -------------------------------- ### Get Media Analysis Results Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Retrieve the analysis results for a given request ID. The result object includes the overall status, confidence score, and model-specific details. ```typescript const result = await realityDefender.getResult(requestId); ``` -------------------------------- ### Initialize Reality Defender SDK Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Instantiate the Reality Defender client with your API key. An optional custom base URL can be provided for specific deployment needs. ```typescript const realityDefender = new RealityDefender({ apiKey: string, baseUrl?: string }); ``` -------------------------------- ### RealityDefender Constructor Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Initializes a new Reality Defender SDK instance with API authentication. An API key is required. ```APIDOC ## RealityDefender Constructor Creates a new Reality Defender SDK instance with API authentication. The API key is required and can be obtained from the Reality Defender Platform at https://app.realitydefender.ai by navigating to Settings > API Keys. ### Request Body - **apiKey** (string) - Required - Your Reality Defender API key. - **baseUrl** (string) - Optional - Custom base URL for the API (e.g., for development environments). ### Request Example ```typescript import { RealityDefender } from '@realitydefender/realitydefender'; // Initialize with API key const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); // Initialize with custom base URL (for development environments) const realityDefenderDev = new RealityDefender({ apiKey: process.env.REALITY_DEFENDER_API_KEY!, baseUrl: 'https://api.dev.realitydefender.xyz', }); ``` ``` -------------------------------- ### Clone Repository Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Clone the Reality Defender SDK repository from GitHub to your local machine. ```bash git clone https://github.com/Reality-Defender/realitydefender-sdk-typescript.git cd realitydefender-sdk-typescript ``` -------------------------------- ### Detect Media (Upload and Analyze) Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Upload a file and initiate media analysis in a single step. Configure polling options for asynchronous result retrieval. ```typescript const result = await realityDefender.detect({ filePath: string }, { maxAttempts?: number, pollingInterval?: number }); ``` -------------------------------- ### Two-Step Upload and Analysis Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Utilize a two-step approach by first uploading a file using `upload` and then retrieving results with `getResult` using the returned `requestId`. This provides more control and is useful for progress tracking. ```typescript import { RealityDefender } from '@realitydefender/realitydefender'; // Initialize the SDK with your API key const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function detectMedia() { try { // Upload a file for analysis const {requestId} = await realityDefender.upload({ filePath: '/path/to/your/file.jpg', }); //Await results using the requestId const result = await realityDefender.getResult(requestId); // Process the results console.log(`Status: ${result.status}`); console.log(`Score: ${result.score}`); // Score is a value between 0 and 1 // List model results result.models.forEach(model => { console.log(`${model.name}: ${model.status} (${model.score})`); // Model scores are also between 0 and 1 }); return result; } catch (error: any) { console.error(`Error: ${error.message} (${error.code})`); throw error; } } // Call the function detectMedia() .then(result => console.log('Detection completed successfully')) .catch(error => console.error('Detection failed')); ``` -------------------------------- ### Analyze Media with detect Method Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Use the detect method for single-step media analysis. This method combines file upload and result retrieval with automatic polling until analysis completes. Configure polling attempts and interval as needed. ```typescript import { RealityDefender, RealityDefenderError } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function analyzeMedia() { try { const result = await realityDefender.detect( { filePath: '/path/to/media.jpg' }, { maxAttempts: 60, // Maximum polling attempts pollingInterval: 3000, // Poll every 3 seconds } ); console.log(`Status: ${result.status}`); // "MANIPULATED", "AUTHENTIC", or "ANALYZING" console.log(`Score: ${result.score?.toFixed(2)}`); // 0-1 confidence score result.models.forEach(model => { console.log(`${model.name}: ${model.status} (${model.score?.toFixed(2)})`); }); return result; } catch (error) { if (error instanceof RealityDefenderError) { console.error(`Error: ${error.message} (${error.code})`); } throw error; } } analyzeMedia(); // Expected output: // Status: MANIPULATED // Score: 0.87 // ModelA: MANIPULATED (0.92) // ModelB: MANIPULATED (0.85) ``` -------------------------------- ### Upload Media for Analysis with upload Method Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Upload a file for analysis using the upload method to obtain tracking IDs for later result retrieval. This provides more control over the analysis process and allows for deferred result retrieval. ```typescript import { RealityDefender, RealityDefenderError } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function uploadMedia() { try { const { requestId, mediaId } = await realityDefender.upload({ filePath: '/path/to/video.mp4', }); console.log(`Request ID: ${requestId}`); console.log(`Media ID: ${mediaId}`); // Store requestId for later result retrieval return { requestId, mediaId }; } catch (error) { if (error instanceof RealityDefenderError) { console.error(`Upload failed: ${error.message} (${error.code})`); // Error codes: 'invalid_file', 'file_too_large', 'upload_failed', 'unauthorized' } throw error; } } uploadMedia(); // Expected output: // Request ID: abc123-def456-ghi789 // Media ID: media-xyz-123 ``` -------------------------------- ### Analyze Social Media Content with SDK Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Uploads a social media link for analysis. Supports YouTube, Facebook, Instagram, Twitter, and TikTok. The API fetches and analyzes media content from the provided URL. Handles potential RealityDefenderErrors. ```typescript import { RealityDefender, RealityDefenderError, DetectionResult } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: process.env.REALITY_DEFENDER_API_KEY!, }); async function analyzeSocialMedia(socialLink: string) { try { // Upload the social media link const { requestId } = await realityDefender.uploadSocialMedia({ socialLink: socialLink, }); console.log(`Upload successful! Request ID: ${requestId}`); // Wait for analysis results const result: DetectionResult = await realityDefender.getResult(requestId, { maxAttempts: 24, // Wait up to 2 minutes pollingInterval: 5000, // Check every 5 seconds }); console.log(`Status: ${result.status}`); console.log(`Confidence: ${result.score ? (result.score * 100).toFixed(2) + '%' : 'N/A'}`); result.models.forEach(model => { const score = model.score ? (model.score * 100).toFixed(2) + '%' : 'N/A'; console.log(` ${model.name}: ${model.status} (${score})`); }); return result; } catch (error) { if (error instanceof RealityDefenderError) { console.error(`Error: ${error.message} (Code: ${error.code})`); // Error codes: 'invalid_request' (invalid URL), 'upload_failed', 'unauthorized' } throw error; } } // Analyze YouTube video analyzeSocialMedia('https://www.youtube.com/watch?v=ABC123'); // Analyze TikTok post analyzeSocialMedia('https://www.tiktok.com/@user/video/1234567890'); // Expected output: // Upload successful! Request ID: xyz789-abc123 // Status: MANIPULATED // Confidence: 78.50% // AudioAnalyzer: MANIPULATED (82.30%) // VisualAnalyzer: MANIPULATED (74.70%) ``` -------------------------------- ### upload - Upload Media for Analysis Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Uploads a file to Reality Defender for analysis and returns tracking IDs for later result retrieval. Use this for more control over the analysis process or when you need to store the requestId for deferred result retrieval. ```APIDOC ## POST /api/v1/upload Uploads a file to Reality Defender for analysis and returns tracking IDs for later result retrieval. ### Method POST ### Endpoint /api/v1/upload ### Parameters #### Request Body - **filePath** (string) - Required - The local path to the media file to upload. - **url** (string) - Optional - The URL of the media to upload. ### Request Example ```typescript import { RealityDefender, RealityDefenderError } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function uploadMedia() { try { const { requestId, mediaId } = await realityDefender.upload({ filePath: '/path/to/video.mp4', }); console.log(`Request ID: ${requestId}`); console.log(`Media ID: ${mediaId}`); return { requestId, mediaId }; } catch (error) { if (error instanceof RealityDefenderError) { console.error(`Upload failed: ${error.message} (${error.code})`); } throw error; } } uploadMedia(); ``` ### Response #### Success Response (200) - **requestId** (string) - A unique identifier for the upload request. - **mediaId** (string) - A unique identifier for the uploaded media. #### Response Example ```json { "requestId": "abc123-def456-ghi789", "mediaId": "media-xyz-123" } ``` ### Error Handling - **invalid_file**: The provided file is not a valid media format. - **file_too_large**: The uploaded file exceeds the maximum allowed size. - **upload_failed**: An error occurred during the file upload process. - **unauthorized**: The provided API key is invalid or lacks the necessary permissions. ``` -------------------------------- ### Detect Media Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Uploads and analyzes media in a single step, polling for results until completion. ```APIDOC ## detect(options, pollingOptions) ### Description Uploads a file and automatically polls for the detection result. ### Parameters #### Request Body - **filePath** (string) - Required - Path to the file to analyze - **maxAttempts** (number) - Optional - Maximum polling attempts - **pollingInterval** (number) - Optional - Interval in ms to poll for results (default: 5000) ### Response #### Success Response (200) - **result** (DetectionResult) - The final detection result object ``` -------------------------------- ### Handle RealityDefender Errors Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Demonstrates how to catch and handle specific errors from the RealityDefender SDK using a switch statement on the error code. Ensure to import RealityDefenderError and ErrorCode. ```typescript import { RealityDefender, RealityDefenderError, ErrorCode } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function handleErrors() { try { await realityDefender.detect({ filePath: '/invalid/path.jpg' }); } catch (error) { if (error instanceof RealityDefenderError) { console.log(`Error Message: ${error.message}`); console.log(`Error Code: ${error.code}`); console.log(`Error Name: ${error.name}`); // Always 'RealityDefenderError' // Handle specific error codes switch (error.code as ErrorCode) { case 'unauthorized': console.log('Invalid or missing API key'); break; case 'invalid_file': console.log('File not found or unsupported format'); break; case 'file_too_large': console.log('File exceeds size limit'); break; case 'upload_failed': console.log('Failed to upload file'); break; case 'not_found': console.log('Request ID not found'); break; case 'timeout': console.log('Operation timed out'); break; case 'server_error': console.log('Server-side error'); break; case 'invalid_request': console.log('Invalid request parameters'); break; case 'unknown_error': console.log('Unexpected error occurred'); break; } } } } // File size limits by type: // Video (.mp4, .mov): 250 MB // Image (.jpg, .png, .jpeg, .gif, .webp): 50 MB // Audio (.flac, .wav, .mp3, .m4a, .aac, .alac, .ogg): 20 MB // Text (.txt): 5 MB handleErrors(); ``` -------------------------------- ### Upload Media for Analysis Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Upload a file for media analysis. This method returns a request ID and media ID for subsequent result retrieval. Configure polling and timeout settings. ```typescript const result = await realityDefender.upload({ filePath: string, pollingInterval?: number, timeout?: number }); ``` -------------------------------- ### Error Handling with RealityDefenderError Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Implement try-catch blocks to handle potential errors during SDK operations. Differentiate between various error codes for specific recovery strategies. ```typescript try { const result = await realityDefender.upload({ filePath: '/path/to/file.jpg' }); } catch (error) { if (error instanceof RealityDefenderError) { console.error(`Error: ${error.message} (${error.code})`); } } ``` -------------------------------- ### Upload Media Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md Uploads media for analysis and returns identifiers for tracking. ```APIDOC ## upload(options) ### Description Uploads a file for analysis and returns the request and media identifiers. ### Parameters #### Request Body - **filePath** (string) - Required - Path to the file to analyze - **pollingInterval** (number) - Optional - Interval in ms to poll for results (default: 5000) - **timeout** (number) - Optional - Timeout in ms for polling (default: 300000) ### Response #### Success Response (200) - **requestId** (string) - Unique identifier for the analysis request - **mediaId** (string) - Unique identifier for the uploaded media ``` -------------------------------- ### Retrieve Detection Results with getResult Source: https://context7.com/reality-defender/realitydefender-sdk-typescript/llms.txt Fetches analysis results for a specific request ID, including automatic polling until completion. Requires handling of RealityDefenderError for API-specific exceptions. ```typescript import { RealityDefender, RealityDefenderError } from '@realitydefender/realitydefender'; const realityDefender = new RealityDefender({ apiKey: 'your-api-key', }); async function getAnalysisResult(requestId: string) { try { const result = await realityDefender.getResult(requestId, { maxAttempts: 12, // Maximum polling attempts (default: unlimited) pollingInterval: 5000, // Poll every 5 seconds (default: 5000ms) }); console.log(`Request ID: ${result.requestId}`); console.log(`Status: ${result.status}`); console.log(`Overall Score: ${result.score !== null ? result.score.toFixed(2) : 'N/A'}`); // Iterate through individual model results console.log('Model Results:'); result.models.forEach(model => { const scoreStr = model.score !== null ? model.score.toFixed(2) : 'N/A'; console.log(` - ${model.name}: ${model.status} (Score: ${scoreStr})`); }); return result; } catch (error) { if (error instanceof RealityDefenderError) { console.error(`Error: ${error.message} (${error.code})`); // Error codes: 'not_found', 'timeout', 'unauthorized', 'server_error' } throw error; } } getAnalysisResult('abc123-def456-ghi789'); // Expected output: // Request ID: abc123-def456-ghi789 // Status: AUTHENTIC // Overall Score: 0.12 // Model Results: // - DeepfakeDetector: AUTHENTIC (Score: 0.10) // - FaceSwapAnalyzer: AUTHENTIC (Score: 0.15) ``` -------------------------------- ### Detection Result Structure Source: https://github.com/reality-defender/realitydefender-sdk-typescript/blob/main/README.md The DetectionResult object provides detailed analysis outcomes, including overall status, confidence score, and individual model assessments. ```typescript { status: string, score: number, models: [ { name: string, status: string, score: number } ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.