File size: 8,356 Bytes
96af7c9 b068b76 96af7c9 |
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 |
/**
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* HUGGING FACE MODELS INTEGRATION
* Using Popular HF Models for Crypto Analysis
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
*/
class HuggingFaceIntegration {
constructor() {
this.apiEndpoint = '/static-proxy?url=https%3A%2F%2Fapi-inference.huggingface.co%2Fmodels%26%23x27%3B%3C%2Fspan%3E%3B
this.models = {
sentiment: 'cardiffnlp/twitter-roberta-base-sentiment-latest',
emotion: 'j-hartmann/emotion-english-distilroberta-base',
textClassification: 'distilbert-base-uncased-finetuned-sst-2-english',
summarization: 'facebook/bart-large-cnn',
translation: 'Helsinki-NLP/opus-mt-en-fa'
};
this.cache = new Map();
this.init();
}
init() {
this.setupSentimentAnalysis();
this.setupNewsSummarization();
this.setupEmotionDetection();
}
/**
* Sentiment Analysis using HF Model
*/
async analyzeSentiment(text) {
const cacheKey = `sentiment_${text.substring(0, 50)}`;
if (this.cache.has(cacheKey)) {
return this.cache.get(cacheKey);
}
try {
const response = await fetch(`${this.apiEndpoint}/${this.models.sentiment}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.getApiKey()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ inputs: text })
});
if (!response.ok) {
throw new Error(`HF API error: ${response.status}`);
}
const data = await response.json();
const result = this.processSentimentResult(data);
this.cache.set(cacheKey, result);
return result;
} catch (error) {
console.error('Sentiment analysis error:', error);
return this.getFallbackSentiment(text);
}
}
processSentimentResult(data) {
if (Array.isArray(data) && data[0]) {
const scores = data[0];
return {
label: scores[0]?.label || 'NEUTRAL',
score: scores[0]?.score || 0.5,
confidence: Math.round(scores[0]?.score * 100) || 50
};
}
return { label: 'NEUTRAL', score: 0.5, confidence: 50 };
}
getFallbackSentiment(text) {
// Simple fallback sentiment analysis
const positiveWords = ['good', 'great', 'excellent', 'bullish', 'up', 'rise', 'gain', 'profit'];
const negativeWords = ['bad', 'terrible', 'bearish', 'down', 'fall', 'loss', 'crash'];
const lowerText = text.toLowerCase();
const positiveCount = positiveWords.filter(w => lowerText.includes(w)).length;
const negativeCount = negativeWords.filter(w => lowerText.includes(w)).length;
if (positiveCount > negativeCount) {
return { label: 'POSITIVE', score: 0.7, confidence: 70 };
} else if (negativeCount > positiveCount) {
return { label: 'NEGATIVE', score: 0.3, confidence: 70 };
}
return { label: 'NEUTRAL', score: 0.5, confidence: 50 };
}
/**
* News Summarization
*/
async summarizeNews(text, maxLength = 100) {
const cacheKey = `summary_${text.substring(0, 50)}`;
if (this.cache.has(cacheKey)) {
return this.cache.get(cacheKey);
}
try {
const response = await fetch(`${this.apiEndpoint}/${this.models.summarization}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.getApiKey()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
inputs: text,
parameters: { max_length: maxLength, min_length: 30 }
})
});
if (!response.ok) {
throw new Error(`HF API error: ${response.status}`);
}
const data = await response.json();
const summary = Array.isArray(data) ? data[0]?.summary_text : data.summary_text;
this.cache.set(cacheKey, summary);
return summary || text.substring(0, maxLength) + '...';
} catch (error) {
console.error('Summarization error:', error);
return text.substring(0, maxLength) + '...';
}
}
/**
* Emotion Detection
*/
async detectEmotion(text) {
try {
const response = await fetch(`${this.apiEndpoint}/${this.models.emotion}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.getApiKey()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ inputs: text })
});
if (!response.ok) {
throw new Error(`HF API error: ${response.status}`);
}
const data = await response.json();
return this.processEmotionResult(data);
} catch (error) {
console.error('Emotion detection error:', error);
return { label: 'neutral', score: 0.5 };
}
}
processEmotionResult(data) {
if (Array.isArray(data) && data[0]) {
const emotions = data[0];
const topEmotion = emotions.reduce((max, curr) =>
curr.score > max.score ? curr : max
);
return {
label: topEmotion.label,
score: topEmotion.score,
confidence: Math.round(topEmotion.score * 100)
};
}
return { label: 'neutral', score: 0.5, confidence: 50 };
}
/**
* Setup sentiment analysis for news
*/
setupSentimentAnalysis() {
// Analyze news sentiment when news is loaded
document.addEventListener('newsLoaded', async (e) => {
const newsItems = e.detail;
for (const item of newsItems) {
if (item.title && !item.sentiment) {
item.sentiment = await this.analyzeSentiment(item.title + ' ' + (item.description || ''));
}
}
// Dispatch event with analyzed news
document.dispatchEvent(new CustomEvent('newsAnalyzed', { detail: newsItems }));
});
}
/**
* Setup news summarization
*/
setupNewsSummarization() {
document.addEventListener('newsLoaded', async (e) => {
const newsItems = e.detail;
for (const item of newsItems) {
if (item.description && item.description.length > 200 && !item.summary) {
item.summary = await this.summarizeNews(item.description, 100);
}
}
});
}
/**
* Setup emotion detection
*/
setupEmotionDetection() {
// Can be used for social media posts, comments, etc.
window.detectEmotion = async (text) => {
return await this.detectEmotion(text);
};
}
/**
* Get API Key (should be set in environment or config)
*/
getApiKey() {
// Priority: window.HF_API_KEY > DASHBOARD_CONFIG.HF_TOKEN > default
return window.HF_API_KEY ||
(window.DASHBOARD_CONFIG && window.DASHBOARD_CONFIG.HF_TOKEN) ||
'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';
}
}
// Initialize HF integration
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
window.hfIntegration = new HuggingFaceIntegration();
});
} else {
window.hfIntegration = new HuggingFaceIntegration();
}
|