Spaces:
Sleeping
Sleeping
File size: 9,670 Bytes
ca2c89c |
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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
// API utilities for NLP Ultimate Tutorial Flask Application
class NLPAPI {
constructor(baseUrl = '') {
this.baseUrl = baseUrl;
this.endpoints = {
// Text processing endpoints
preprocessing: '/api/preprocessing',
tokenization: '/api/tokenization',
posTagging: '/api/pos-tagging',
namedEntity: '/api/named-entity',
sentiment: '/api/sentiment',
summarization: '/api/summarization',
topicAnalysis: '/api/topic-analysis',
questionAnswering: '/api/question-answering',
textGeneration: '/api/text-generation',
translation: '/api/translation',
classification: '/api/classification',
vectorEmbeddings: '/api/vector-embeddings',
// Utility endpoints
updateText: '/api/update_current_text',
getText: '/api/get_current_text',
textStatistics: '/api/text_statistics'
};
}
// Generic API request method
async request(endpoint, data = {}, method = 'POST') {
try {
const response = await fetch(this.baseUrl + endpoint, {
method: method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error(`API request failed for ${endpoint}:`, error);
throw error;
}
}
// Text preprocessing
async preprocessText(text, options = {}) {
return await this.request(this.endpoints.preprocessing, {
text: text,
...options
});
}
// Tokenization
async tokenizeText(text, tokenizerType = 'word') {
return await this.request(this.endpoints.tokenization, {
text: text,
tokenizer_type: tokenizerType
});
}
// POS Tagging
async posTagText(text, taggerType = 'nltk') {
return await this.request(this.endpoints.posTagging, {
text: text,
tagger_type: taggerType
});
}
// Named Entity Recognition
async recognizeEntities(text, modelType = 'spacy') {
return await this.request(this.endpoints.namedEntity, {
text: text,
model_type: modelType
});
}
// Sentiment Analysis
async analyzeSentiment(text, analyzerType = 'vader') {
return await this.request(this.endpoints.sentiment, {
text: text,
analyzer_type: analyzerType
});
}
// Text Summarization
async summarizeText(text, method = 'extractive', options = {}) {
return await this.request(this.endpoints.summarization, {
text: text,
method: method,
...options
});
}
// Topic Analysis
async analyzeTopics(text, method = 'lda') {
return await this.request(this.endpoints.topicAnalysis, {
text: text,
method: method
});
}
// Question Answering
async answerQuestion(context, question, options = {}) {
return await this.request(this.endpoints.questionAnswering, {
context: context,
question: question,
...options
});
}
// Text Generation
async generateText(prompt, options = {}) {
return await this.request(this.endpoints.textGeneration, {
prompt: prompt,
...options
});
}
// Translation
async translateText(text, sourceLang = 'auto', targetLang = 'en') {
return await this.request(this.endpoints.translation, {
text: text,
source_lang: sourceLang,
target_lang: targetLang
});
}
// Classification
async classifyText(text, scenario = 'sentiment', options = {}) {
return await this.request(this.endpoints.classification, {
text: text,
scenario: scenario,
...options
});
}
// Vector Embeddings
async getEmbeddings(text, query = '') {
return await this.request(this.endpoints.vectorEmbeddings, {
text: text,
query: query
});
}
// Utility methods
async updateCurrentText(text) {
return await this.request(this.endpoints.updateText, { text: text });
}
async getCurrentText() {
return await this.request(this.endpoints.getText, {}, 'GET');
}
async getTextStatistics(text) {
return await this.request(this.endpoints.textStatistics, { text: text });
}
}
// Batch processing utility
class BatchProcessor {
constructor(api) {
this.api = api;
this.queue = [];
this.processing = false;
}
addTask(task) {
this.queue.push(task);
if (!this.processing) {
this.processQueue();
}
}
async processQueue() {
this.processing = true;
while (this.queue.length > 0) {
const task = this.queue.shift();
try {
await task.execute();
if (task.onSuccess) task.onSuccess(task.result);
} catch (error) {
if (task.onError) task.onError(error);
}
}
this.processing = false;
}
}
// Caching utility
class APICache {
constructor(maxSize = 100) {
this.cache = new Map();
this.maxSize = maxSize;
}
get(key) {
if (this.cache.has(key)) {
const item = this.cache.get(key);
// Move to end (most recently used)
this.cache.delete(key);
this.cache.set(key, item);
return item;
}
return null;
}
set(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.maxSize) {
// Remove least recently used item
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
clear() {
this.cache.clear();
}
}
// Rate limiting utility
class RateLimiter {
constructor(requestsPerMinute = 60) {
this.requestsPerMinute = requestsPerMinute;
this.requests = [];
}
async waitIfNeeded() {
const now = Date.now();
const oneMinuteAgo = now - 60000;
// Remove old requests
this.requests = this.requests.filter(time => time > oneMinuteAgo);
if (this.requests.length >= this.requestsPerMinute) {
const oldestRequest = Math.min(...this.requests);
const waitTime = 60000 - (now - oldestRequest);
if (waitTime > 0) {
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
this.requests.push(now);
}
}
// Error handling utility
class ErrorHandler {
static handle(error, context = '') {
console.error(`Error in ${context}:`, error);
let message = 'An unexpected error occurred';
if (error.name === 'TypeError' && error.message.includes('fetch')) {
message = 'Network error: Unable to connect to the server';
} else if (error.message.includes('HTTP error')) {
message = `Server error: ${error.message}`;
} else if (error.message) {
message = error.message;
}
return {
success: false,
error: message,
context: context,
timestamp: new Date().toISOString()
};
}
static createErrorResponse(message, context = '') {
return {
success: false,
error: message,
context: context,
timestamp: new Date().toISOString()
};
}
}
// Progress tracking utility
class ProgressTracker {
constructor() {
this.progress = 0;
this.total = 0;
this.callbacks = [];
}
setTotal(total) {
this.total = total;
this.progress = 0;
this.notifyCallbacks();
}
increment(amount = 1) {
this.progress += amount;
this.notifyCallbacks();
}
setProgress(progress) {
this.progress = progress;
this.notifyCallbacks();
}
onProgress(callback) {
this.callbacks.push(callback);
}
notifyCallbacks() {
const percentage = this.total > 0 ? (this.progress / this.total) * 100 : 0;
this.callbacks.forEach(callback => callback(percentage, this.progress, this.total));
}
reset() {
this.progress = 0;
this.total = 0;
this.notifyCallbacks();
}
}
// Export utilities
window.NLPAPI = NLPAPI;
window.BatchProcessor = BatchProcessor;
window.APICache = APICache;
window.RateLimiter = RateLimiter;
window.ErrorHandler = ErrorHandler;
window.ProgressTracker = ProgressTracker;
|