import React, { useState, useEffect } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { Key, Plus, Trash2, Copy, Check, Eye, EyeOff, Code, FileText, AlertCircle, Clock, Sparkles, ExternalLink, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; import { cn } from "@/lib/utils"; import { createAPIKey, listAPIKeys, deleteAPIKey } from "@/services/api"; const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "https://seth0330-ezofisocr.hf.space"; export default function APIKeys() { const [apiKeys, setApiKeys] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [showCreateModal, setShowCreateModal] = useState(false); const [newKeyName, setNewKeyName] = useState(""); const [isCreating, setIsCreating] = useState(false); const [newlyCreatedKey, setNewlyCreatedKey] = useState(null); const [copiedKeyId, setCopiedKeyId] = useState(null); const [visibleKeys, setVisibleKeys] = useState(new Set()); // Fetch API keys on mount useEffect(() => { fetchAPIKeys(); }, []); const fetchAPIKeys = async () => { setIsLoading(true); setError(null); try { const response = await listAPIKeys(); setApiKeys(response.api_keys || []); } catch (err) { setError(err.message || "Failed to load API keys"); } finally { setIsLoading(false); } }; const handleCreateKey = async () => { if (!newKeyName.trim()) { setError("Please enter a name for your API key"); return; } setIsCreating(true); setError(null); try { const response = await createAPIKey(newKeyName.trim()); setNewlyCreatedKey(response.api_key); setNewKeyName(""); setShowCreateModal(false); await fetchAPIKeys(); } catch (err) { setError(err.message || "Failed to create API key"); } finally { setIsCreating(false); } }; const handleDeleteKey = async (keyId) => { if (!confirm("Are you sure you want to deactivate this API key? This action cannot be undone.")) { return; } try { await deleteAPIKey(keyId); await fetchAPIKeys(); } catch (err) { setError(err.message || "Failed to delete API key"); } }; const copyToClipboard = (text, keyId = null) => { navigator.clipboard.writeText(text); if (keyId) { setCopiedKeyId(keyId); setTimeout(() => setCopiedKeyId(null), 2000); } }; const toggleKeyVisibility = (keyId) => { const newVisible = new Set(visibleKeys); if (newVisible.has(keyId)) { newVisible.delete(keyId); } else { newVisible.add(keyId); } setVisibleKeys(newVisible); }; const formatDate = (dateString) => { if (!dateString) return "Never"; const date = new Date(dateString); return date.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); }; return (
{/* Header */}

API Keys

Manage API keys for external application access

{/* Main Content */}
{/* Error Message */} {error && (

Error

{error}

)} {/* Success Message for New Key */} {newlyCreatedKey && (

API Key Created Successfully!

⚠️ Store this key securely - it will not be shown again.

Your API Key
{newlyCreatedKey}
)} {/* API Keys List */}
{isLoading ? (

Loading API keys...

) : apiKeys.length === 0 ? (

No API Keys Yet

Create your first API key to start using the API from external applications

) : (
{apiKeys.map((key) => (

{key.name}

{key.is_active ? ( Active ) : ( Inactive )}
{key.key_prefix}
Created: {formatDate(key.created_at)}
{key.last_used_at && (
Last used: {formatDate(key.last_used_at)}
)}
))}
)}
{/* API Usage Guide */}

How to Use API Keys

Integrate document parsing into your external applications

{/* Python Example */}

Python Example

                  {`import requests

API_URL = "${API_BASE_URL}"
API_KEY = "sk_live_YOUR_API_KEY_HERE"

def extract_document(file_path, key_fields=None):
    with open(file_path, 'rb') as f:
        files = {'file': f}
        data = {}
        if key_fields:
            data['key_fields'] = key_fields
        
        response = requests.post(
            f"{API_URL}/api/extract",
            headers={"X-API-Key": API_KEY},
            files=files,
            data=data
        )
        return response.json()

# Usage
result = extract_document("invoice.pdf", 
    key_fields="Invoice Number,Invoice Date")
print(result)`}
                
{/* cURL Example */}

cURL Example

                  {`curl -X POST ${API_BASE_URL}/api/extract \\
  -H "X-API-Key: sk_live_YOUR_API_KEY_HERE" \\
  -F "file=@document.pdf" \\
  -F "key_fields=Invoice Number,Invoice Date,Total Amount"`}
                
{/* JavaScript Example */}

JavaScript/Node.js Example

                  {`const FormData = require('form-data');
const fs = require('fs');
const axios = require('axios');

const API_URL = '${API_BASE_URL}';
const API_KEY = 'sk_live_YOUR_API_KEY_HERE';

async function extractDocument(filePath, keyFields = null) {
  const form = new FormData();
  form.append('file', fs.createReadStream(filePath));
  if (keyFields) {
    form.append('key_fields', keyFields);
  }

  const response = await axios.post(
    \`\${API_URL}/api/extract\`,
    form,
    {
      headers: {
        'X-API-Key': API_KEY,
        ...form.getHeaders()
      }
    }
  );
  return response.data;
}

// Usage
extractDocument('invoice.pdf', 'Invoice Number,Invoice Date')
  .then(result => console.log(result));`}
                

API Endpoint

POST {API_BASE_URL}/api/extract

• Max file size: 4 MB • Supported formats: PDF, PNG, JPEG, TIFF

{/* Create API Key Modal */} {showCreateModal && ( !isCreating && setShowCreateModal(false)} > e.stopPropagation()} className="bg-white rounded-2xl p-6 max-w-md w-full shadow-2xl" >

Create New API Key

Give your API key a descriptive name to identify it later

setNewKeyName(e.target.value)} className="mb-6" onKeyPress={(e) => e.key === "Enter" && handleCreateKey()} />
)}
); }