Spaces:
Sleeping
Sleeping
File size: 23,368 Bytes
caa2485 | 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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | from flask import Flask, render_template_string, request, jsonify
from flask_cors import CORS
from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline
import os
import sys
import threading
import time
app = Flask(__name__)
CORS(app)
# Model loading state (thread-safe)
model_name = "openai/privacy-filter"
classifier = None
model_loading = False
model_error = None
model_thread = None
# Background model loading
def load_model_async():
global classifier, model_loading, model_error
model_loading = True
print("="*60, flush=True)
print("BACKGROUND: Loading OpenAI Privacy Filter model...", flush=True)
print("="*60, flush=True)
try:
print(f"Loading tokenizer and model: {model_name}", flush=True)
print("This may take 5-10 minutes on first run...", flush=True)
# Use AutoModelForTokenClassification directly for better performance
tokenizer = AutoTokenizer.from_pretrained(
model_name,
cache_dir="/app/.cache/huggingface"
)
model = AutoModelForTokenClassification.from_pretrained(
model_name,
cache_dir="/app/.cache/huggingface"
)
global classifier
classifier = pipeline(
task="token-classification",
model=model,
tokenizer=tokenizer,
aggregation_strategy="simple",
device=-1 # Force CPU
)
print("✓ Model loaded successfully!", flush=True)
model_error = None
except Exception as e:
model_error = str(e)
print(f"✗ ERROR loading model: {e}", flush=True)
import traceback
traceback.print_exc()
finally:
model_loading = False
# Start model loading in background
model_thread = threading.Thread(target=load_model_async, daemon=True)
model_thread.start()
# HTML Template with proper loading states
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenAI Privacy Filter - PII Detection Demo</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
min-height: 100vh;
color: #fff;
padding: 20px;
}
.container { max-width: 900px; margin: 0 auto; }
h1 {
text-align: center; margin-bottom: 10px;
background: linear-gradient(90deg, #00d4ff, #7b2cbf);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 2.5rem;
}
.subtitle { text-align: center; color: #8892b0; margin-bottom: 30px; }
.card {
background: rgba(255,255,255,0.05);
border-radius: 12px;
padding: 25px;
margin-bottom: 20px;
backdrop-filter: blur(10px);
border: 1px solid rgba(255,255,255,0.1);
}
textarea {
width: 100%; min-height: 150px; padding: 15px;
border-radius: 8px; border: 1px solid rgba(255,255,255,0.2);
background: rgba(0,0,0,0.3); color: #fff;
font-size: 14px; resize: vertical; font-family: monospace;
}
textarea::placeholder { color: #666; }
button {
width: 100%; padding: 15px; margin-top: 15px;
border: none; border-radius: 8px;
background: linear-gradient(90deg, #00d4ff, #7b2cbf);
color: #fff; font-size: 16px; font-weight: 600;
cursor: pointer; transition: transform 0.2s, box-shadow 0.2s;
}
button:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 5px 25px rgba(0,212,255,0.4);
}
button:disabled {
opacity: 0.6; cursor: not-allowed;
background: linear-gradient(90deg, #666, #444);
}
.results { display: none; }
.results.active { display: block; }
.result-text {
background: rgba(0,0,0,0.3); padding: 20px;
border-radius: 8px; font-family: monospace;
line-height: 1.8; word-wrap: break-word;
white-space: pre-wrap;
}
.entity {
padding: 2px 8px; border-radius: 4px;
font-weight: bold;
}
.entity-private_person { background: rgba(255,107,107,0.3); border: 1px solid #ff6b6b; }
.entity-private_email { background: rgba(78,205,196,0.3); border: 1px solid #4ecdc4; }
.entity-private_phone { background: rgba(255,209,102,0.3); border: 1px solid #ffd166; }
.entity-private_address { background: rgba(6,214,160,0.3); border: 1px solid #06d6a0; }
.entity-account_number { background: rgba(239,71,111,0.3); border: 1px solid #ef476f; }
.entity-secret { background: rgba(255,0,110,0.3); border: 1px solid #ff006e; }
.entity-private_url { background: rgba(131,56,236,0.3); border: 1px solid #8338ec; }
.entity-private_date { background: rgba(58,134,255,0.3); border: 1px solid #3a86ff; }
.legend {
display: flex; flex-wrap: wrap; gap: 10px;
margin-top: 15px; justify-content: center;
}
.legend-item {
display: flex; align-items: center;
gap: 5px; font-size: 12px;
}
.legend-color {
width: 20px; height: 20px;
border-radius: 4px; border: 1px solid;
}
.details-list { margin-top: 20px; }
.detail-item {
display: flex; justify-content: space-between;
align-items: center; padding: 12px;
background: rgba(255,255,255,0.03);
border-radius: 6px; margin-bottom: 8px;
}
.detail-type { font-weight: bold; color: #00d4ff; }
.detail-score { font-size: 12px; color: #8892b0; }
.error-box {
background: rgba(239,71,111,0.2);
border: 1px solid #ef476f;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
color: #ff6b6b;
}
.info-box {
background: rgba(0,212,255,0.1);
border-left: 3px solid #00d4ff;
padding: 15px; margin-bottom: 20px;
border-radius: 0 8px 8px 0;
}
.info-box h3 { margin-bottom: 5px; }
.info-box ul { margin-left: 20px; color: #8892b0; }
.status-indicator {
display: inline-block;
width: 10px; height: 10px;
border-radius: 50%;
margin-right: 8px;
}
.status-ok { background: #06d6a0; }
.status-error { background: #ef476f; }
.status-loading { background: #ffd166; animation: pulse 1s infinite; }
.status-waiting { background: #3a86ff; }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
#modelStatus {
text-align: center;
margin-bottom: 15px;
padding: 15px;
background: rgba(0,0,0,0.3);
border-radius: 8px;
font-size: 14px;
}
.loading-spinner {
display: inline-block;
width: 20px; height: 20px;
border: 3px solid rgba(255,255,255,0.3);
border-top-color: #00d4ff;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-right: 10px;
vertical-align: middle;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.progress-bar {
width: 100%;
height: 4px;
background: rgba(255,255,255,0.1);
border-radius: 2px;
margin-top: 10px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #00d4ff, #7b2cbf);
animation: progress 2s ease-in-out infinite;
}
@keyframes progress {
0% { width: 0%; transform: translateX(-100%); }
50% { width: 70%; transform: translateX(50%); }
100% { width: 0%; transform: translateX(200%); }
}
</style>
</head>
<body>
<div class="container">
<h1>OpenAI Privacy Filter</h1>
<p class="subtitle">PII Detection & Masking Demo using Flask</p>
<div id="modelStatus">
<span id="statusIndicator" class="status-indicator status-loading"></span>
<span id="statusText">Waiting for server to start...</span>
<div class="progress-bar" id="progressBar">
<div class="progress-fill"></div>
</div>
</div>
<div class="info-box">
<h3>Detects 8 Types of PII:</h3>
<ul>
<li><strong>private_person</strong> - Names and personal identifiers</li>
<li><strong>private_email</strong> - Email addresses</li>
<li><strong>private_phone</strong> - Phone numbers</li>
<li><strong>private_address</strong> - Physical addresses</li>
<li><strong>account_number</strong> - Account/ID numbers</li>
<li><strong>secret</strong> - Passwords, tokens, credentials</li>
<li><strong>private_url</strong> - Personal/private URLs</li>
<li><strong>private_date</strong> - Personal dates (birthdays, etc.)</li>
</ul>
</div>
<div class="card">
<textarea id="inputText" placeholder="Enter text with PII here...\n\nExample: My name is Alice Smith and my email is alice.smith@example.com. You can reach me at (555) 123-4567 or visit me at 123 Main Street, New York. My SSN is 123-45-6789."></textarea>
<button onclick="analyzeText()" id="analyzeBtn" disabled>Waiting for model...</button>
<div id="errorBox" class="error-box" style="display: none;"></div>
</div>
<div class="card results" id="resultsCard">
<h3 style="margin-bottom: 15px;">Results</h3>
<div class="result-text" id="resultDisplay"></div>
<div class="legend">
<div class="legend-item"><div class="legend-color entity-private_person"></div> Person</div>
<div class="legend-item"><div class="legend-color entity-private_email"></div> Email</div>
<div class="legend-item"><div class="legend-color entity-private_phone"></div> Phone</div>
<div class="legend-item"><div class="legend-color entity-private_address"></div> Address</div>
<div class="legend-item"><div class="legend-color entity-account_number"></div> Account</div>
<div class="legend-item"><div class="legend-color entity-secret"></div> Secret</div>
<div class="legend-item"><div class="legend-color entity-private_url"></div> URL</div>
<div class="legend-item"><div class="legend-color entity-private_date"></div> Date</div>
</div>
<div class="details-list" id="detailsList"></div>
</div>
</div>
<script>
let statusCheckInterval = null;
let isModelLoaded = false;
let retryCount = 0;
const maxRetries = 200; // 16 minutes of retrying (200 * 5 seconds)
function updateStatus(state, message) {
const statusIndicator = document.getElementById("statusIndicator");
const statusText = document.getElementById("statusText");
const progressBar = document.getElementById("progressBar");
const btn = document.getElementById("analyzeBtn");
switch(state) {
case 'connecting':
statusIndicator.className = "status-indicator status-waiting";
statusText.innerHTML = `<span class="loading-spinner"></span>${message}`;
btn.disabled = true;
btn.textContent = "Server is starting up...";
progressBar.style.display = "block";
break;
case 'loading':
statusIndicator.className = "status-indicator status-loading";
statusText.innerHTML = `<span class="loading-spinner"></span>${message}`;
btn.disabled = true;
btn.textContent = "Model is loading...";
progressBar.style.display = "block";
break;
case 'ready':
statusIndicator.className = "status-indicator status-ok";
statusText.innerHTML = "✓ " + message;
btn.disabled = false;
btn.textContent = "Detect PII";
progressBar.style.display = "none";
break;
case 'error':
statusIndicator.className = "status-indicator status-error";
statusText.innerHTML = "✗ " + message;
btn.disabled = true;
btn.textContent = "Model unavailable";
progressBar.style.display = "none";
break;
}
}
// Check model status on page load and keep polling
async function checkModelStatus() {
retryCount++;
if (retryCount > maxRetries) {
updateStatus('error', 'Server did not respond after 16 minutes. Refresh to retry.');
clearInterval(statusCheckInterval);
statusCheckInterval = null;
// Show reload button
updateStatus('error', 'Server did not respond. <button onclick="location.reload()">Refresh Page</button>');
return;
}
try {
const response = await fetch("/health", {
method: "GET",
headers: { "Cache-Control": "no-cache" }
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
console.log("Health check response:", data);
if (data.model_loading) {
// Still loading
updateStatus('loading', `Model loading initialized... (5-10 minutes on first run)`);
if (!statusCheckInterval) {
statusCheckInterval = setInterval(checkModelStatus, 5000);
}
isModelLoaded = false;
} else if (data.model_loaded) {
// Model ready
updateStatus('ready', 'Model loaded and ready');
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
statusCheckInterval = null;
}
isModelLoaded = true;
retryCount = 0;
} else {
// Model failed
updateStatus('error', `Model failed: ${data.error || "Unknown error"}`);
const errorBox = document.getElementById("errorBox");
errorBox.style.display = "block";
errorBox.innerHTML = `<strong>Error:</strong> ${data.error || "Unknown error"}`;
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
statusCheckInterval = null;
}
isModelLoaded = false;
}
} catch (error) {
console.error("Health check failed:", error);
// Server not ready yet, show connecting state
updateStatus('connecting', `Waiting for server to start... (attempt ${retryCount})`);
if (!statusCheckInterval) {
statusCheckInterval = setInterval(checkModelStatus, 5000);
}
}
}
// Start checking immediately with connecting state
checkModelStatus();
async function analyzeText() {
const text = document.getElementById("inputText").value;
const btn = document.getElementById("analyzeBtn");
const resultsCard = document.getElementById("resultsCard");
const errorBox = document.getElementById("errorBox");
if (!text.trim()) {
errorBox.style.display = "block";
errorBox.textContent = "Please enter some text first!";
return;
}
btn.disabled = true;
btn.innerHTML = '<span class="loading-spinner"></span>Analyzing...';
errorBox.style.display = "none";
try {
const response = await fetch("/analyze", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: text })
});
const data = await response.json();
if (!response.ok || !data.success) {
throw new Error(data.error || "Server error");
}
displayResults(data, text);
resultsCard.classList.add("active");
} catch (error) {
console.error("Error during analysis:", error);
errorBox.style.display = "block";
errorBox.textContent = "Error: " + error.message;
resultsCard.classList.remove("active");
} finally {
if (isModelLoaded) {
btn.disabled = false;
btn.textContent = "Detect PII";
}
}
}
function displayResults(data, originalText) {
let html = "";
let lastEnd = 0;
if (data.entities && data.entities.length > 0) {
const sorted = data.entities.sort((a, b) => a.start - b.start);
for (const entity of sorted) {
html += escapeHtml(originalText.slice(lastEnd, entity.start));
html += `<span class="entity entity-${entity.label}">${escapeHtml(entity.text)}</span>`;
lastEnd = entity.end;
}
html += escapeHtml(originalText.slice(lastEnd));
const detailsHtml = sorted.map(e => `
<div class="detail-item">
<div>
<span class="detail-type">${e.label}</span>: ${escapeHtml(e.text)}
</div>
<div class="detail-score">Score: ${(e.score * 100).toFixed(2)}%</div>
</div>
`).join("");
document.getElementById("detailsList").innerHTML = "<h4 style='margin:20px 0 10px 0;'>Detected Entities:</h4>" + detailsHtml;
} else {
html = escapeHtml(originalText) + "\\n\\n[No PII detected]";
document.getElementById("detailsList").innerHTML = "";
}
document.getElementById("resultDisplay").innerHTML = html;
}
function escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
// Cleanup on page unload
window.addEventListener("beforeunload", () => {
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
}
});
// Add keyboard shortcut (Ctrl+Enter to analyze)
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('inputText').addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 'Enter') {
analyzeText();
}
});
});
</script>
</body>
</html>
'''
@app.route('/')
def index():
return render_template_string(HTML_TEMPLATE)
@app.route('/health')
def health():
"""Health check with model loading status"""
global classifier, model_loading, model_error, model_thread
if classifier is not None:
return jsonify({
'status': 'healthy',
'model_loaded': True,
'model_loading': False
})
elif model_loading:
return jsonify({
'status': 'loading',
'model_loaded': False,
'model_loading': True,
'message': 'Model is still loading, please wait...'
})
else:
# Model failed or thread died
return jsonify({
'status': 'unhealthy',
'model_loaded': False,
'model_loading': False,
'error': model_error or 'Model loading failed or thread terminated unexpectedly'
}), 503
@app.route('/analyze', methods=['POST', 'OPTIONS'])
def analyze():
if request.method == 'OPTIONS':
return '', 204
global classifier, model_loading
if classifier is None:
return jsonify({
'success': False,
'error': f'Model not yet loaded. Current status: {"loading" if model_loading else "failed"}. Please wait and refresh in a few minutes.'
}), 503
try:
data = request.get_json()
if not data:
return jsonify({'success': False, 'error': 'No JSON data received'}), 400
text = data.get('text', '')
if not text.strip():
return jsonify({'success': True, 'entities': [], 'entity_count': 0})
# Run classification
results = classifier(text)
entities = []
for entity in results:
entities.append({
'label': entity.get('entity_group', entity.get('entity', 'unknown')),
'text': entity.get('word', ''),
'start': entity.get('start', 0),
'end': entity.get('end', 0),
'score': float(entity.get('score', 0))
})
return jsonify({
'success': True,
'entities': entities,
'entity_count': len(entities)
})
except Exception as e:
print(f"Error during analysis: {e}", flush=True)
import traceback
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e)
}), 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port, debug=False, threaded=True) |