Spaces:
Sleeping
Sleeping
File size: 20,027 Bytes
65781b1 c452442 65781b1 c452442 1b5c906 c452442 51741f3 65781b1 c452442 51741f3 c452442 51741f3 65781b1 51741f3 c452442 65781b1 db81103 65781b1 db81103 65781b1 db81103 65781b1 db81103 65781b1 db81103 65781b1 db81103 65781b1 db81103 65781b1 5c7f2f8 65781b1 5c7f2f8 65781b1 5c7f2f8 65781b1 5c7f2f8 65781b1 5c7f2f8 65781b1 5c7f2f8 65781b1 c452442 5c7f2f8 51741f3 65781b1 51741f3 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 51741f3 65781b1 51741f3 65781b1 737ac7f 65781b1 737ac7f 65781b1 e3d51ef 737ac7f e3d51ef 65781b1 737ac7f c452442 e3d51ef c452442 e3d51ef 65781b1 737ac7f 65781b1 51741f3 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 51741f3 65781b1 51741f3 65781b1 c452442 65781b1 c452442 65781b1 c452442 51741f3 65781b1 51741f3 65781b1 c452442 65781b1 b71b6f0 65781b1 c452442 65781b1 c452442 65781b1 b71b6f0 51741f3 65781b1 51741f3 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 65781b1 c452442 51741f3 65781b1 51741f3 65781b1 94cb6fe 51741f3 65781b1 51741f3 c452442 65781b1 c452442 65781b1 51741f3 65781b1 | 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 | # predict.py - Optimized Production Version with Enhanced Accuracy & Performance
from transformers import (
DistilBertTokenizerFast,
DistilBertForSequenceClassification,
DistilBertConfig,
AutoTokenizer,
AutoModelForSequenceClassification
)
import torch
import torch.nn.functional as F
import numpy as np
import logging
import os
import json
import shutil
import re
import time
from typing import Tuple, List, Optional, Dict
from functools import lru_cache
import threading
# =======================
# Logging configuration
# =======================
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# =======================
# Global variables with thread safety
# =======================
model = None
tokenizer = None
model_loaded = False
model_lock = threading.Lock()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logger.info(f"Using device: {device}")
# Performance tracking
inference_times = []
# Load slang keywords with caching
DRUG_KEYWORDS = []
HIGH_RISK_KEYWORDS = []
# ========================
# Enhanced keyword loading with caching
# ========================
@lru_cache(maxsize=1)
def load_keywords(file_path="slang_keywords.txt") -> List[str]:
"""Load keywords with caching for performance"""
if not os.path.exists(file_path):
logger.warning(f"Keyword file not found: {file_path}. Using default keywords.")
return []
try:
with open(file_path, "r", encoding='utf-8') as f:
keywords = [line.strip().lower() for line in f if line.strip() and not line.startswith('#')]
logger.info(f"Loaded {len(keywords)} slang keywords from {file_path}")
return keywords
except Exception as e:
logger.error(f"Failed to load keywords from {file_path}: {e}")
return []
@lru_cache(maxsize=1)
def load_high_risk_keywords(file_path="high_risk_keywords.txt") -> List[str]:
"""Load high-risk keywords with caching"""
if not os.path.exists(file_path):
logger.warning(f"High-risk keyword file not found: {file_path}")
return ["cocaine", "heroin", "mdma", "lsd", "meth", "fentanyl", "dealer", "supplier"]
try:
with open(file_path, "r", encoding='utf-8') as f:
keywords = [line.strip().lower() for line in f if line.strip() and not line.startswith('#')]
logger.info(f"Loaded {len(keywords)} high-risk keywords from {file_path}")
return keywords
except Exception as e:
logger.error(f"Failed to load high-risk keywords: {e}")
return ["cocaine", "heroin", "mdma", "lsd", "meth", "fentanyl", "dealer", "supplier"]
# Initialize global keywords
DRUG_KEYWORDS = load_keywords("slang_keywords.txt")
HIGH_RISK_KEYWORDS = load_high_risk_keywords("high_risk_keywords.txt")
# =======================
# Enhanced text preprocessing for better accuracy
# =======================
def preprocess_text(text: str) -> str:
"""Enhanced text preprocessing for better model accuracy"""
if not text:
return ""
# Convert to lowercase
text = text.lower()
# Remove excessive whitespace but preserve sentence structure
text = re.sub(r'\s+', ' ', text)
# Handle common abbreviations and slang normalization
abbreviations = {
'u': 'you',
'ur': 'your',
'n': 'and',
'w/': 'with',
'thru': 'through',
'gonna': 'going to',
'wanna': 'want to',
'gotta': 'got to'
}
for abbrev, full in abbreviations.items():
text = re.sub(rf'\b{re.escape(abbrev)}\b', full, text)
# Remove excessive punctuation but keep sentence boundaries
text = re.sub(r'[!]{2,}', '!', text)
text = re.sub(r'[?]{2,}', '?', text)
text = re.sub(r'[.]{3,}', '...', text)
return text.strip()
# =======================
# Enhanced keyword-based scoring
# =======================
def compute_keyword_score(text: str) -> Tuple[float, Dict[str, int]]:
"""Compute keyword-based score for enhanced accuracy"""
text_lower = text.lower()
# =======================
# Enhanced text preprocessing for better accuracy
# =======================
def preprocess_text(text: str) -> str:
"""Enhanced text preprocessing for better model accuracy"""
if not text:
return ""
# Convert to lowercase
text = text.lower()
# Remove excessive whitespace but preserve sentence structure
text = re.sub(r'\s+', ' ', text)
# Handle common abbreviations and slang normalization
abbreviations = {
'u': 'you',
'ur': 'your',
'n': 'and',
'w/': 'with',
'thru': 'through',
'gonna': 'going to',
'wanna': 'want to',
'gotta': 'got to'
}
for abbrev, full in abbreviations.items():
text = re.sub(rf'\b{re.escape(abbrev)}\b', full, text)
# Remove excessive punctuation but keep sentence boundaries
text = re.sub(r'[!]{2,}', '!', text)
text = re.sub(r'[?]{2,}', '?', text)
text = re.sub(r'[.]{3,}', '...', text)
return text.strip()
# =======================
# Enhanced keyword-based scoring
# =======================
def compute_keyword_score(text: str) -> Tuple[float, Dict[str, int]]:
"""Compute keyword-based score for enhanced accuracy"""
text_lower = text.lower()
AMBIGUOUS_TERMS = {"e", "x", "line", "ice", "horse", "420"}
def keyword_check_with_context(text: str, kw: str) -> bool:
pattern = rf"\b{re.escape(kw)}\b"
if re.search(pattern, text, re.IGNORECASE):
if kw in AMBIGUOUS_TERMS:
context_pattern = r"\b(smoke|roll|pop|hit|take|buy|sell|party|snort|inject)\b"
return bool(re.search(context_pattern, text, re.IGNORECASE))
return True
return False
def compute_keyword_score(text: str) -> Tuple[float, Dict[str, int]]:
"""Compute keyword-based score for enhanced accuracy"""
text_lower = text.lower()
drug_matches = sum(1 for kw in DRUG_KEYWORDS if keyword_check_with_context(text_lower, kw))
high_risk_matches = sum(1 for kw in HIGH_RISK_KEYWORDS if keyword_check_with_context(text_lower, kw))
context_patterns = [
r'(?i)(pick.*up|got.*stuff|meet.*behind)',
r'(?i)(payment|crypto|cash.*deal)',
r'(?i)(supplier|dealer|connect)',
r'(?i)(party.*saturday|rave.*tonight)',
r'(?i)(quality.*good|pure.*stuff)',
r'(?i)(cops.*around|too.*risky)'
]
context_matches = sum(1 for pattern in context_patterns if re.search(pattern, text_lower))
keyword_score = 0.0
if high_risk_matches > 0:
keyword_score += min(high_risk_matches * 0.3, 0.8)
if drug_matches > 0:
keyword_score += min(drug_matches * 0.1, 0.3)
if context_matches > 0:
keyword_score += min(context_matches * 0.15, 0.4)
keyword_score = min(keyword_score, 1.0)
return keyword_score, {
'drug_keywords': drug_matches,
'high_risk_keywords': high_risk_matches,
'context_patterns': context_matches
}
# =======================
# Config validation/fix with enhanced error handling
# =======================
def validate_and_fix_config(model_path: str) -> bool:
"""Validate and fix model configuration if needed"""
config_path = os.path.join(model_path, "config.json")
if not os.path.exists(config_path):
logger.warning(f"Config file not found at {config_path}")
return False
try:
with open(config_path, 'r', encoding='utf-8') as f:
config_data = json.load(f)
# Validate critical dimensions
dim = config_data.get('dim', 768)
n_heads = config_data.get('n_heads', 12)
if dim % n_heads != 0:
logger.warning(f"Configuration issue detected: dim={dim} not divisible by n_heads={n_heads}")
# Create backup
backup_path = config_path + ".backup"
if not os.path.exists(backup_path):
shutil.copy2(config_path, backup_path)
logger.info(f"Backed up original config to {backup_path}")
# Fix configuration with standard DistilBERT dimensions
config_data.update({
'dim': 768,
'n_heads': 12,
'hidden_dim': 3072,
'n_layers': 6,
'vocab_size': 30522,
'max_position_embeddings': 512,
'dropout': 0.1,
'attention_dropout': 0.1,
'activation': 'gelu',
'num_labels': 2
})
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(config_data, f, indent=2)
logger.info("Fixed configuration with standard DistilBERT dimensions")
logger.info("Configuration validation completed")
return True
except Exception as e:
logger.error(f"Error validating/fixing config: {e}")
return False
# =======================
# Enhanced model loading with multiple fallback strategies
# =======================
def load_model_with_fallback(model_name: str) -> bool:
"""Use standard model - bypass custom model for now"""
global model, tokenizer, model_loaded
with model_lock:
if model_loaded:
return True
logger.info("Using standard DistilBERT model (custom model has tokenizer issues)")
try:
tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')
model = AutoModelForSequenceClassification.from_pretrained(
'distilbert-base-uncased',
num_labels=2
)
model.to(device)
model.eval()
model_loaded = True
logger.info("Standard model loaded successfully")
return True
except Exception as e:
logger.error(f"Model loading failed: {e}")
return False
# =======================
# Optimized prediction function with enhanced accuracy
# =======================
def predict(text: str, return_confidence: bool = True) -> Tuple[int, float]:
"""
Enhanced prediction with improved accuracy and performance
Args:
text: Input text to classify
return_confidence: Whether to return confidence scores
Returns:
Tuple of (prediction_label, confidence_score)
"""
start_time = time.time()
try:
# Input validation
if not text or not text.strip():
logger.warning("Empty input text")
return 0, 0.0
# Check if model is loaded
if not model_loaded or model is None or tokenizer is None:
logger.error("Model not loaded properly")
return 0, 0.0
# Preprocess text for better accuracy
processed_text = preprocess_text(text)
# Get keyword-based score
keyword_score, keyword_stats = compute_keyword_score(processed_text)
# Tokenize with proper handling
try:
inputs = tokenizer(
processed_text,
return_tensors="pt",
padding=True,
truncation=True,
max_length=512,
add_special_tokens=True
)
inputs = {k: v.to(device) for k, v in inputs.items()}
except Exception as e:
logger.error(f"Tokenization failed: {e}")
return 0, 0.0
# Model inference with no_grad for performance
with torch.no_grad():
try:
outputs = model(**inputs)
logits = outputs.logits
# Apply softmax to get probabilities
probabilities = F.softmax(logits, dim=-1)
ml_confidence = probabilities[0][1].item() # Probability of drug class
ml_prediction = int(ml_confidence > 0.5)
except Exception as e:
logger.error(f"Model inference failed: {e}")
return 0, 0.0
# Enhanced decision making combining ML and keywords
final_prediction, final_confidence = combine_predictions(
ml_prediction, ml_confidence, keyword_score, keyword_stats, processed_text
)
# Log performance metrics
inference_time = time.time() - start_time
inference_times.append(inference_time)
# Keep only last 100 timing records
if len(inference_times) > 100:
inference_times.pop(0)
logger.info(f"Prediction completed in {inference_time:.3f}s - "
f"Result: {'DRUG' if final_prediction == 1 else 'NON_DRUG'} "
f"(confidence: {final_confidence:.3f}, keyword_score: {keyword_score:.3f})")
return final_prediction, final_confidence
except Exception as e:
logger.error(f"Prediction failed: {e}")
return 0, 0.0
# =======================
# Enhanced prediction combination logic
# =======================
def combine_predictions(ml_pred: int, ml_conf: float, keyword_score: float,
keyword_stats: Dict[str, int], text: str) -> Tuple[int, float]:
"""
Combine ML prediction with keyword-based scoring for better accuracy
"""
try:
# Weight calculation based on keyword evidence
high_risk_count = keyword_stats.get('high_risk_keywords', 0)
drug_count = keyword_stats.get('drug_keywords', 0)
context_count = keyword_stats.get('context_patterns', 0)
# Determine weights based on keyword strength
if high_risk_count >= 2:
ml_weight, keyword_weight = 0.2, 0.8
elif high_risk_count >= 1 or drug_count >= 3:
ml_weight, keyword_weight = 0.3, 0.7
elif drug_count >= 2 or context_count >= 2:
ml_weight, keyword_weight = 0.4, 0.6
else:
ml_weight, keyword_weight = 0.7, 0.3
# Combine scores
combined_score = (ml_weight * ml_conf) + (keyword_weight * keyword_score)
# Enhanced decision logic
if high_risk_count >= 1:
# High-risk keywords present - likely drug content
final_pred = 1
final_conf = max(combined_score, 0.7)
elif keyword_score >= 0.5:
# Strong keyword evidence
final_pred = 1
final_conf = combined_score
elif keyword_score >= 0.3 and ml_conf >= 0.3:
# Moderate evidence from both
final_pred = 1
final_conf = combined_score
elif ml_conf >= 0.7:
# High ML confidence
final_pred = 1
final_conf = combined_score
else:
# Low confidence overall
final_pred = 0
final_conf = max(combined_score, 0.1)
# Ensure confidence is in valid range
final_conf = max(0.0, min(1.0, final_conf))
return final_pred, final_conf
except Exception as e:
logger.error(f"Prediction combination failed: {e}")
return ml_pred, ml_conf
# =======================
# Model management functions
# =======================
def load_model(model_path: str) -> bool:
"""Load model with enhanced error handling"""
try:
success = load_model_with_fallback(model_path)
if success:
logger.info(f"Model loaded successfully from {model_path}")
# Log model info
if model:
param_count = sum(p.numel() for p in model.parameters())
logger.info(f"Model parameters: {param_count:,}")
logger.info(f"Model device: {next(model.parameters()).device}")
else:
logger.error(f"Failed to load model from {model_path}")
return success
except Exception as e:
logger.error(f"Model loading error: {e}")
return False
def is_model_loaded() -> bool:
"""Check if model is properly loaded"""
return model_loaded and model is not None and tokenizer is not None
def get_model_info() -> Dict:
"""Get information about the loaded model"""
if not is_model_loaded():
return {"status": "not_loaded"}
try:
param_count = sum(p.numel() for p in model.parameters())
avg_inference_time = np.mean(inference_times) if inference_times else 0.0
return {
"status": "loaded",
"model_type": type(model).__name__,
"tokenizer_type": type(tokenizer).__name__,
"device": str(device),
"parameters": param_count,
"avg_inference_time": avg_inference_time,
"total_predictions": len(inference_times),
"drug_keywords_count": len(DRUG_KEYWORDS),
"high_risk_keywords_count": len(HIGH_RISK_KEYWORDS)
}
except Exception as e:
logger.error(f"Error getting model info: {e}")
return {"status": "error", "error": str(e)}
# =======================
# Batch prediction for performance
# =======================
def predict_batch(texts: List[str], batch_size: int = 8) -> List[Tuple[int, float]]:
"""
Batch prediction for improved performance on multiple texts
"""
if not texts:
return []
if not is_model_loaded():
logger.error("Model not loaded for batch prediction")
return [(0, 0.0) for _ in texts]
results = []
try:
# Process in batches
for i in range(0, len(texts), batch_size):
batch_texts = texts[i:i + batch_size]
batch_results = []
# Process each text in the batch
for text in batch_texts:
pred, conf = predict(text)
batch_results.append((pred, conf))
results.extend(batch_results)
logger.info(f"Batch prediction completed for {len(texts)} texts")
return results
except Exception as e:
logger.error(f"Batch prediction failed: {e}")
return [(0, 0.0) for _ in texts]
# =======================
# Performance monitoring
# =======================
def get_performance_stats() -> Dict:
"""Get performance statistics"""
if not inference_times:
return {"status": "no_data"}
return {
"total_predictions": len(inference_times),
"avg_inference_time": np.mean(inference_times),
"min_inference_time": min(inference_times),
"max_inference_time": max(inference_times),
"std_inference_time": np.std(inference_times),
"device": str(device)
}
# =======================
# Module initialization
# =======================
def initialize_model(model_path: str = None) -> bool:
"""Initialize the prediction module"""
if model_path:
return load_model(model_path)
return False
# =======================
# Main execution for testing
# =======================
if __name__ == "__main__":
# Test the prediction system
test_texts = [
"Hey, can you pick up some stuff from behind the metro station?",
"I'm going to the grocery store to buy some milk and bread.",
"The quality is really good this time, payment through crypto as usual.",
"Let's meet for coffee tomorrow morning at 9 AM."
]
print("Testing prediction system...")
for i, text in enumerate(test_texts):
pred, conf = predict(text)
result = "DRUG" if pred == 1 else "NON_DRUG"
print(f"Text {i+1}: {result} (confidence: {conf:.3f})")
print(f" Input: {text}")
print()
# Print performance stats
stats = get_performance_stats()
print("Performance Stats:", stats)
# Print model info
info = get_model_info()
print("Model Info:", info) |