File size: 8,395 Bytes
0c1c66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Global API Configuration
const API_CONFIG = {
    HUGGING_FACE_API_KEY: 'your-huggingface-api-key-here', // Replace with actual API key
    BASE_URL: 'https://api-inference.huggingface.co/models/',
    MODELS: {
        TEXT_GENERATION: 'gpt2',
        IMAGE_GENERATION: 'runwayml/stable-diffusion-v1-5',
        SENTIMENT_ANALYSIS: 'cardiffnlp/twitter-roberta-base-sentiment-latest',
        TRANSLATION: 'Helsinki-NLP/opus-mt-en-fr',
        CODE_GENERATION: 'microsoft/DialoGPT-medium',
        AUDIO_PROCESSING: 'facebook/wav2vec2-base-960h'
    }
};

// Utility Functions
class AgentUtils {
    static async makeAPIRequest(endpoint, data, model) {
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}${model}`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${API_CONFIG.HUGGING_FACE_API_KEY}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                throw new Error(`API request failed: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('API Request Error:', error);
            throw error;
        }
    }

    static formatResponse(data, agentType) {
        switch (agentType) {
            case 'text':
                return data[0]?.generated_text || 'No response generated';
            case 'image':
                return data;
            case 'sentiment':
                return this.formatSentiment(data);
            case 'translation':
                return data[0]?.translation_text || 'Translation failed';
            case 'code':
                return data[0]?.generated_text || 'No code generated';
            default:
                return data;
        }
    }

    static formatSentiment(data) {
        if (!Array.isArray(data)) return 'Unable to analyze sentiment';
        
        const scores = data[0];
        if (!scores) return 'No sentiment data available';

        const labels = ['Negative', 'Neutral', 'Positive'];
        const maxScore = Math.max(...scores);
        const maxIndex = scores.indexOf(maxScore);
        
        return {
            sentiment: labels[maxIndex],
            confidence: (maxScore * 100).toFixed(2),
            scores: scores.map((score, index) => ({
                label: labels[index],
                score: (score * 100).toFixed(2)
            })
        };
    }

    static showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 fade-in ${
            type === 'error' ? 'bg-red-500 text-white' :
            type === 'success' ? 'bg-green-500 text-white' :
            'bg-blue-500 text-white'
        }`;
        notification.textContent = message;
        document.body.appendChild(notification);

        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    static toggleLoading(element, show) {
        if (show) {
            element.disabled = true;
            element.innerHTML = '<div class="loading-spinner"></div> Processing...';
        } else {
            element.disabled = false;
            element.textContent = element.dataset.originalText || 'Submit';
        }
    }
}

// Agent Base Class
class BaseAgent {
    constructor(type, model) {
        this.type = type;
        this.model = model;
    }

    async process(input) {
        try {
            const data = await AgentUtils.makeAPIRequest('', { inputs: input }, this.model);
            return AgentUtils.formatResponse(data, this.type);
        } catch (error) {
            AgentUtils.showNotification(`Agent error: ${error.message}`, 'error');
            throw error;
        }
    }
}

// Specific Agent Classes
class TextGenerationAgent extends BaseAgent {
    constructor() {
        super('text', API_CONFIG.MODELS.TEXT_GENERATION);
    }
}

class ImageGenerationAgent extends BaseAgent {
    constructor() {
        super('image', API_CONFIG.MODELS.IMAGE_GENERATION);
    }

    async process(prompt) {
        try {
            const data = await AgentUtils.makeAPIRequest('', { inputs: prompt }, this.model);
            return data;
        } catch (error) {
            AgentUtils.showNotification(`Image generation failed: ${error.message}`, 'error');
            throw error;
        }
    }
}

class SentimentAnalysisAgent extends BaseAgent {
    constructor() {
        super('sentiment', API_CONFIG.MODELS.SENTIMENT_ANALYSIS);
    }
}

class TranslationAgent extends BaseAgent {
    constructor() {
        super('translation', API_CONFIG.MODELS.TRANSLATION);
    }
}

class CodeGenerationAgent extends BaseAgent {
    constructor() {
        super('code', API_CONFIG.MODELS.CODE_GENERATION);
    }
}

class AudioProcessingAgent extends BaseAgent {
    constructor() {
        super('audio', API_CONFIG.MODELS.AUDIO_PROCESSING);
    }
}

// Agent Manager
class AgentManager {
    constructor() {
        this.agents = {
            text: new TextGenerationAgent(),
            image: new ImageGenerationAgent(),
            sentiment: new SentimentAnalysisAgent(),
            translation: new TranslationAgent(),
            code: new CodeGenerationAgent(),
            audio: new AudioProcessingAgent()
        };
    }

    getAgent(type) {
        return this.agents[type];
    }

    async executeAgent(type, input) {
        const agent = this.getAgent(type);
        if (!agent) {
            throw new Error(`Agent type '${type}' not found`);
        }
        return await agent.process(input);
    }
}

// Initialize Agent Manager
const agentManager = new AgentManager();

// Event Listeners for Agent Pages
document.addEventListener('DOMContentLoaded', function() {
    // Text Generation Form
    const textForm = document.getElementById('text-generation-form');
    if (textForm) {
        textForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const input = document.getElementById('text-input').value;
            const submitBtn = document.getElementById('text-submit-btn');
            
            if (!input.trim()) {
                AgentUtils.showNotification('Please enter some text', 'error');
                return;
            }

            AgentUtils.toggleLoading(submitBtn, true);
            
            try {
                const result = await agentManager.executeAgent('text', input);
                document.getElementById('text-result').textContent = result;
            } catch (error) {
                console.error('Text generation failed:', error);
            } finally {
                AgentUtils.toggleLoading(submitBtn, false);
            }
        });
    }

    // Image Generation Form
    const imageForm = document.getElementById('image-generation-form');
    if (imageForm) {
        imageForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const prompt = document.getElementById('image-prompt').value;
            const submitBtn = document.getElementById('image-submit-btn');
            
            if (!prompt.trim()) {
                AgentUtils.showNotification('Please enter an image description', 'error');
                return;
            }

            AgentUtils.toggleLoading(submitBtn, true);
            
            try {
                const result = await agentManager.executeAgent('image', prompt);
                // For demo purposes, we'll show a placeholder image
                const imageResult = document.getElementById('image-result');
                imageResult.innerHTML = `
                    <div class="text-center">
                        <img src="http://static.photos/technology/640x360/1" alt="Generated Image" class="rounded-lg mx-auto mb-4">
                        <p class="text-secondary-600">Image generated based on: "${prompt}"</p>
                    </div>
                `;
            } catch (error) {
                console.error('Image generation failed:', error);
            } finally {
                AgentUtils.toggleLoading(submitBtn, false);
            }
        });
    }

    // Add similar event listeners for other agent types...
});