Spaces:
Paused
Paused
Update classify.py
Browse files4 unmodified lines56789101112131415161718192021222324252627288 unmodified lines373839404142434450 unmodified lines95969798991001011021031041 unmodified line10610710810911011111240 unmodified lines1531541551561571581591 unmodified line16116216316416516616712 unmodified lines18018118218318418518618718818913 unmodified lines20320420520620720820921015 unmodified lines2262272282292302312322332344 unmodified linesLegacyCRM β 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_llmLEGACY_SOURCE = "LegacyCRM"# ββ Result type βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ8 unmodified lines# ββ 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)50 unmodified linesdef parallel_llm(idx):src, msg = logs[idx]log_hash = hashlib.md5(msg.encode('utf-8')).hexdigest()t_llm_0 = time.perf_counter()label = cached_llm_call(log_hash, msg)t_llm_ms = (time.perf_counter() - t_llm_0) * 1000base_tier = "LLM" if src == LEGACY_SOURCE else "LLM (fallback)"1 unmodified linereturn 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))for idx, res in llm_results:40 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)1 unmodified linedef 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"}12 unmodified linesresults = []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."),15 unmodified linesprint("\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)")elif "Regex" in tier:print(f" Regex Latency: < 0.1 ms (Recorded p50: {stats['p50_ms']} ms) | count={stats['count']}")else:print(f" {tier}: {stats['count']} logs ({stats['pct']}%) | "4 unmodified lines567891011121314151617181920212223242526272829308 unmodified lines394041424344454650 unmodified lines9798991001011021031041051 unmodified line10710810911011111211311440 unmodified lines1551561571581591601611 unmodified line16316416516616716816912 unmodified lines18218318418518618718818919019119219319419519619713 unmodified lines21121221321421521615 unmodified lines2322332342352362372384 unmodified linesLegacyCRM β LLM directlyOthers β Regex β BERT (batch) β LLM fallbackChanges in V5 (Patched):- Fixed multiprocessing: Switched to ThreadPoolExecutor to properly share the @lru_cache memory across chunks.- Eliminated MD5 cache key collision risks.- Removed hardcoded thread limits to avoid bottlenecks.- Extracted business rules (LegacyCRM) to environment variables.- Corrected misleading batch latency metrics."""from __future__ import annotationsimport osimport timeimport 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_llm# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββLEGACY_SOURCE = os.getenv("LEGACY_SOURCE", "LegacyCRM")# ββ Result type βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ8 unmodified lines# ββ 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_msg: str) -> str:"""Only executes the expensive LLM call if the string misses the cache."""return classify_with_llm(log_msg)50 unmodified linesdef parallel_llm(idx):src, msg = logs[idx]t_llm_0 = time.perf_counter()# Removed redundant MD5 hashing; standard string key is safer and fasterlabel = cached_llm_call(msg)t_llm_ms = (time.perf_counter() - t_llm_0) * 1000base_tier = "LLM" if src == LEGACY_SOURCE else "LLM (fallback)"1 unmodified linereturn idx, _make_result(label, tier, None, t_llm_ms)# Removed hardcoded max_workers=4 to allow auto-scaling based on CPU coreswith ThreadPoolExecutor() as executor:llm_results = list(executor.map(parallel_llm, llm_indices))for idx, res in llm_results:40 unmodified lines# ββ Multiprocessing Helper βββββββββββββββββββββββββββββββββββββββββββββββββββdef _process_chunk(chunk: list[tuple[str, str]]) -> list[dict]:"""Top-level helper function required for ThreadPoolExecutor mapping."""return classify_logs(chunk)1 unmodified linedef classify_csv(input_path: str, output_path: str = "output.csv") -> tuple[str, pd.DataFrame]:"""Ultra-Optimized Batch Processing for 2M+ Logs.Uses ThreadPoolExecutor to share the massive lru_cache across chunks."""df = pd.read_csv(input_path)required = {"source", "log_message"}12 unmodified linesresults = []# Switched to ThreadPoolExecutor so memory (lru_cache) is shared properlyprint(f"π₯ Firing up {max_cores} worker threads to process {len(chunks)} chunks...")t_start = time.perf_counter()with ThreadPoolExecutor(max_workers=max_cores) as executor:for chunk_result in executor.map(_process_chunk, chunks):results.extend(chunk_result)t_end = time.perf_counter()print(f"β±οΈ True Wall-Clock Processing Time: {(t_end - t_start):.2f} seconds")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."),15 unmodified linesprint("\nπ Pipeline Summary:")for tier, stats in summary["tier_stats"].items():if "Regex" in tier:print(f" Regex Latency: < 0.1 ms (Recorded p50: {stats['p50_ms']} ms) | count={stats['count']}")else:print(f" {tier}: {stats['count']} logs ({stats['pct']}%) | "
classify.py+26-22