Spaces:
Paused
Paused
Update classify.py
Browse files12345678910111213141516171819202122237 unmodified lines3132333435363738394041424339 unmodified lines83848586878889907 unmodified lines98991001011021031041 unmodified line10610710810911011111211311411511611711825 unmodified lines1441451461471481491501511521531541553 unmodified lines1591601611621631641651661671681691701 unmodified line17217317417517617717813 unmodified lines1921931941951961971 unmodified line1992002012022032042056 unmodified lines212213214215216217218"""classify.py β 3-Tier Hybrid Pipeline (V4 β MAANG-Grade Telemetry & Caching)Architecture:LegacyCRM β LLM directlyOthers β Regex β BERT (batch) β LLM fallbackChanges in V4:- High-resolution telemetry (4 decimal places) to capture sub-ms Regex execution.- True Batch Latency tracking for BERT (decoupled from individual log spoofing).- MD5 Hashing & LRU Cache layer for the LLM to mathematically prove cost savings.- Parallelized LLM Tier using ThreadPoolExecutor for high throughput."""from __future__ import annotationsimport timeimport hashlibimport statisticsimport pandas as pdfrom functools import lru_cachefrom concurrent.futures import ThreadPoolExecutorfrom processor_regex import classify_with_regexfrom processor_bert import classify_batch as bert_batchfrom processor_llm import classify_with_llm7 unmodified lines"label": label,"tier": tier,"confidence": confidence,# FIX 2: Increased clock resolution to 4 decimal places for sub-ms accuracy"latency_ms": round(latency_ms, 4),}# ββ Caching Layer (FIX 3) βββββββββββββββββββββββββββββββββββββββββββββββββββ@lru_cache(maxsize=10000)def cached_llm_call(log_hash: str, log_msg: str) -> str:"""Only executes the expensive LLM call if the MD5 hash misses the cache."""return classify_with_llm(log_msg)39 unmodified linesbert_results = bert_batch(bert_msgs)t_bert_end = time.perf_counter()# We keep the amortized calculation strictly for the CSV line items,# but the pipeline_summary will handle reporting this as a Batch.bert_ms_per_log = (t_bert_end - t_bert_start) * 1000 / len(bert_msgs)for idx, (label, conf) in zip(bert_indices, bert_results):7 unmodified linesdef parallel_llm(idx):src, msg = logs[idx]# FIX 3: Generate MD5 hash of the log stringlog_hash = hashlib.md5(msg.encode('utf-8')).hexdigest()t_llm_0 = time.perf_counter()1 unmodified linet_llm_ms = (time.perf_counter() - t_llm_0) * 1000base_tier = "LLM" if src == LEGACY_SOURCE else "LLM (fallback)"# Categorize the telemetry based on execution time (Sub 5ms = Memory Hit)tier = f"{base_tier} (Cache Hit)" if t_llm_ms < 5 else f"{base_tier} (API Call)"return idx, _make_result(label, tier, None, t_llm_ms)# Parallelize API calls to prevent pipeline stall, restricted to 4 workers to prevent OOMwith ThreadPoolExecutor(max_workers=4) as executor:llm_results = list(executor.map(parallel_llm, llm_indices))25 unmodified linestier_stats[tier] = {"count": n,"pct": round(n / total * 100, 1),# FIX 2: Prevent flatlining at 0.0 by expanding decimal precision"p50_ms": round(statistics.median(latencies_sorted), 4),"p95_ms": round(latencies_sorted[min(int(n * 0.95), n - 1)], 4),"p99_ms": round(latencies_sorted[min(int(n * 0.99), n - 1)], 4),"mean_ms": round(statistics.mean(latencies_sorted), 4),"total_ms": round(sum(latencies_sorted), 4), # Required for Batch calculation}return {3 unmodified lines}# ββ CSV batch classify βββββββββββββββββββββββββββββββββββββββββββββββββββββββdef classify_csv(input_path: str, output_path: str = "output.csv") -> tuple[str, pd.DataFrame]:"""Process a batch of logs from a CSV file.Required columns: 'source', 'log_message'Output: appends 'predicted_label', 'tier_used', 'confidence', 'latency_ms'"""df = pd.read_csv(input_path)required = {"source", "log_message"}1 unmodified lineraise ValueError(f"Missing required columns in CSV. Expected: {required}. Found: {set(df.columns)}")log_pairs = list(zip(df["source"], df["log_message"]))results = classify_logs(log_pairs)df["predicted_label"] = [r["label"] for r in results]df["tier_used"] = [r["tier"] for r in results]13 unmodified lines# ββ Self-test ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif __name__ == "__main__":sample = [("ModernCRM", "IP 192.168.133.114 blocked due to potential attack"),("BillingSystem", "User User12345 logged in."),1 unmodified line("ModernHR", "GET /v2/servers/detail HTTP/1.1 status: 200 len: 1583 time: 0.19"),("ModernHR", "Admin access escalation detected for user 9429"),("LegacyCRM", "Case escalation for ticket ID 7324 failed because the assigned support agent is no longer active."),("LegacyCRM", "Case escalation for ticket ID 7324 failed because the assigned support agent is no longer active."), # Deliberate duplicate to test MD5 Cache]print(f'{"Source":<20} {"Tier":<22} {"Conf":>6} {"Lat(ms)":>8} {"Label":<25} Log')6 unmodified linessummary = pipeline_summary(results)print("\nπ Pipeline Summary:")# FIX 1: Decoupling the reporting output to reflect architectural realityfor tier, stats in summary["tier_stats"].items():if tier == "BERT":print(f" BERT Batch Latency: {stats['total_ms']} ms (Amortized over {stats['count']} logs)")12345678910111213141516171819202122237 unmodified lines31323334353637383940414239 unmodified lines8283848586877 unmodified lines95969798991001 unmodified line10210310410510610710810911011125 unmodified lines1371381391401411421431441451461473 unmodified lines1511521531541551561571581591601611621631641651661671 unmodified line16917017117217317417517617717817918018118218318418518618718818913 unmodified lines2032042052062072082092101 unmodified line2122132142152162172186 unmodified lines225226227228229230"""classify.py β 3-Tier Hybrid Pipeline (V5 β Multiprocessing & Max RAM Utilization)Architecture:LegacyCRM β LLM directlyOthers β Regex β BERT (batch) β LLM fallbackChanges in V5:- Added ProcessPoolExecutor for classify_csv to distribute workload across all CPU cores.- Increased LRU cache size to 500,000 to maximize RAM usage and minimize LLM calls during 2M+ log stress tests.- High-resolution telemetry and True Batch Latency tracking retained from V4."""from __future__ import annotationsimport osimport timeimport hashlibimport statisticsimport pandas as pdfrom functools import lru_cachefrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutorfrom processor_regex import classify_with_regexfrom processor_bert import classify_batch as bert_batchfrom processor_llm import classify_with_llm7 unmodified lines"label": label,"tier": tier,"confidence": confidence,"latency_ms": round(latency_ms, 4),}# ββ Caching Layer (V5 UPDATE: Max RAM Eater) ββββββββββββββββββββββββββββββββ@lru_cache(maxsize=500000) # Increased to 500k to absorb duplicate logs in 2M+ datasetsdef cached_llm_call(log_hash: str, log_msg: str) -> str:"""Only executes the expensive LLM call if the MD5 hash misses the cache."""return classify_with_llm(log_msg)39 unmodified linesbert_results = bert_batch(bert_msgs)t_bert_end = time.perf_counter()bert_ms_per_log = (t_bert_end - t_bert_start) * 1000 / len(bert_msgs)for idx, (label, conf) in zip(bert_indices, bert_results):7 unmodified linesdef parallel_llm(idx):src, msg = logs[idx]log_hash = hashlib.md5(msg.encode('utf-8')).hexdigest()t_llm_0 = time.perf_counter()1 unmodified linet_llm_ms = (time.perf_counter() - t_llm_0) * 1000base_tier = "LLM" if src == LEGACY_SOURCE else "LLM (fallback)"tier = f"{base_tier} (Cache Hit)" if t_llm_ms < 5 else f"{base_tier} (API Call)"return idx, _make_result(label, tier, None, t_llm_ms)with ThreadPoolExecutor(max_workers=4) as executor:llm_results = list(executor.map(parallel_llm, llm_indices))25 unmodified linestier_stats[tier] = {"count": n,"pct": round(n / total * 100, 1),"p50_ms": round(statistics.median(latencies_sorted), 4),"p95_ms": round(latencies_sorted[min(int(n * 0.95), n - 1)], 4),"p99_ms": round(latencies_sorted[min(int(n * 0.99), n - 1)], 4),"mean_ms": round(statistics.mean(latencies_sorted), 4),"total_ms": round(sum(latencies_sorted), 4),}return {3 unmodified lines}# ββ Multiprocessing Helper βββββββββββββββββββββββββββββββββββββββββββββββββββdef _process_chunk(chunk: list[tuple[str, str]]) -> list[dict]:"""Top-level helper function required for ProcessPoolExecutor mapping."""return classify_logs(chunk)# ββ CSV batch classify (V5 UPDATE: Multi-Core Processor) βββββββββββββββββββββdef classify_csv(input_path: str, output_path: str = "output.csv") -> tuple[str, pd.DataFrame]:"""Ultra-Optimized Batch Processing for 2M+ Logs.Uses ProcessPoolExecutor to max out CPU cores and gorge on RAM."""df = pd.read_csv(input_path)required = {"source", "log_message"}1 unmodified lineraise ValueError(f"Missing required columns in CSV. Expected: {required}. Found: {set(df.columns)}")log_pairs = list(zip(df["source"], df["log_message"]))total_logs = len(log_pairs)# OS ke liye 1 core chhod kar baaki sab use karomax_cores = max(1, os.cpu_count() - 1)# 50,000 logs ke chunks banao (Memory distribution)chunk_size = 50000chunks = [log_pairs[i:i + chunk_size] for i in range(0, total_logs, chunk_size)]results = []print(f"π₯ Firing up {max_cores} CPU cores to process {len(chunks)} chunks...")with ProcessPoolExecutor(max_workers=max_cores) as executor:for chunk_result in executor.map(_process_chunk, chunks):results.extend(chunk_result)df["predicted_label"] = [r["label"] for r in results]df["tier_used"] = [r["tier"] for r in results]13 unmodified lines# ββ Self-test ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif __name__ == "__main__":# Required for safe multiprocessing on Windows/macOS# Ensures child processes don't recursively run the __main__ blocksample = [("ModernCRM", "IP 192.168.133.114 blocked due to potential attack"),("BillingSystem", "User User12345 logged in."),1 unmodified line("ModernHR", "GET /v2/servers/detail HTTP/1.1 status: 200 len: 1583 time: 0.19"),("ModernHR", "Admin access escalation detected for user 9429"),("LegacyCRM", "Case escalation for ticket ID 7324 failed because the assigned support agent is no longer active."),("LegacyCRM", "Case escalation for ticket ID 7324 failed because the assigned support agent is no longer active."),]print(f'{"Source":<20} {"Tier":<22} {"Conf":>6} {"Lat(ms)":>8} {"Label":<25} Log')6 unmodified linessummary = pipeline_summary(results)print("\nπ Pipeline Summary:")for tier, stats in summary["tier_stats"].items():if tier == "BERT":print(f" BERT Batch Latency: {stats['total_ms']} ms (Amortized over {stats['count']} logs)")
classify.py+37-25