Spaces:
Paused
Paused
Replace Gemini with in-Space open-source LLM (Qwen3.5-2B via llama.cpp)
Browse files93 unmodified lines949596979899256 unmodified lines35635735835936036136236336436536636736836937099 unmodified lines4704714724734744751 unmodified line477478479480481482483484485486487488489490491492493494495496497498499500501218 unmodified lines72072172272372472572672772872973031 unmodified lines762763764765766767310 unmodified lines10781079108010811082108324 unmodified lines11081109111011111112111311141115111611174 unmodified lines1122112311241125112611271128112958 unmodified lines11881189119011911192119311942 unmodified lines1197119811991200120112021203120412055 unmodified lines12111212121312141215121612171218121919 unmodified lines123912401241124212431244124512463 unmodified lines125012511252125312541255125612573 unmodified lines1261126212631264126512661267126812691270127120 unmodified lines129212931294129512961297129812992 unmodified lines130213031304130513061307130869 unmodified lines13781379138013811382138313841385138613871388138913901391139218 unmodified lines141114121413141414151416141714184 unmodified lines14231424142514261427142817 unmodified lines14461447144814491450145114528 unmodified lines146114621463146414651466146714689 unmodified lines14781479148014811482148314841485105 unmodified lines159115921593159415951596159715981599160016013 unmodified lines160516061607160816091610161110 unmodified lines16221623162416251626162716283 unmodified lines16321633163416351636163716383 unmodified lines164216431644164516461647164822 unmodified lines167116721673167416751676167785 unmodified lines17631764176517661767176817695 unmodified lines177517761777177817791780178117825 unmodified lines17881789179017911792179317945 unmodified lines18001801180218031804180518063 unmodified lines181018111812181318141815181693 unmodified lines]# ============================================================================# REASONING SERVICE (LLM-backed analysis for the REST API)# ============================================================================256 unmodified linesself.ready = loaded > 0logger.info(f"ML Models: {loaded} loaded — {list(self.models.keys())}")def predict(self, model_name: str, features: Dict) -> Dict:if model_name not in self.models:return self._heuristic_predict(model_name, features)try:model = self.models[model_name]scaler = self.scalers.get(model_name)X = np.array([list(features.values())])if scaler:X = scaler.transform(X)prediction = int(model.predict(X)[0])confidence = 0.5probabilities = {}99 unmodified lines}ml_loader = MLModelLoader()1 unmodified line# URL FEATURE EXTRACTION# ============================================================================def extract_url_features(url: str) -> Dict:parsed = urlparse(url)hostname = parsed.hostname or ""return {"url_length": len(url),"hostname_length": len(hostname),"path_length": len(parsed.path or ""),"is_https": 1 if parsed.scheme == "https" else 0,"has_ip_address": 1 if all(p.isdigit() for p in hostname.split(".")) and len(hostname.split(".")) == 4 else 0,"has_suspicious_tld": 1 if any(hostname.endswith(t) for t in [".xyz", ".tk", ".ml", ".ga", ".cf", ".top", ".buzz"]) else 0,"subdomain_count": max(0, len(hostname.split(".")) - 2),"has_port": 1 if parsed.port else 0,"query_params_count": len(parsed.query.split("&")) if parsed.query else 0,"has_at_symbol": 1 if "@" in url else 0,"has_double_slash": 1 if "//" in (parsed.path or "") else 0,"special_char_count": sum(1 for c in url if c in "!@#$%^&*()+={}[]|\\:;<>?,"),}# ============================================================================# TRANSFORMER MODEL LOADER (Phase 3 — real HF transformer models)# ============================================================================218 unmodified linesdef predict_dga(self, domain: str) -> Dict:"""Detect DGA-generated domains using a Shannon-entropy + character-pattern heuristic.Real DGA domains have high entropy, low pronounceability, no real word substrings."""import mathd = domain.lower().strip().split('.')[0][:60] # SLD only, ignore TLDif not d:return {"model": "dga_detector", "error": "empty domain"}# Shannon entropy of character distributionfrom collections import Counterfreq = Counter(d)31 unmodified lines"is_threat": is_dga,"confidence": round(score * 100, 2) if is_dga else round((1 - score) * 100, 2),"threat_score": round(score, 4),"features": {"entropy": round(entropy, 3),"vowel_ratio": round(vowel_ratio, 3),310 unmodified lines)@api.get("/health")async def api_health():return {24 unmodified lines@api.post("/analyze")async def api_analyze(request: Request):"""Main analysis endpoint – called by backend mlService.chatWithAI()"""body = await request.json()query = body.get("query", "")context = body.get("context", {})history = body.get("conversation_history", [])result = await run_in_threadpool(reasoning_service.analyze, query, context, history)return result4 unmodified linesReturns per-model predictions + unified aggregate with risk_score (0-100).All models now consistently include threat_score (probability of class-1)."""body = await request.json()url = body.get("url", "")if not url:return JSONResponse(status_code=400, content={"detail": "URL required"})features = extract_url_features(url)58 unmodified lines@api.post("/scan-threats")async def api_scan_threats(request: Request):"""Threat scanning – called by backend mlService.scanForThreats()"""body = await request.json()query = json.dumps(body.get("data", body), indent=1)[:3000]result = await run_in_threadpool(reasoning_service.analyze, f"Scan these indicators for threats:\n{query}")return result2 unmodified lines@api.post("/api/insights/generate")async def api_generate_insights(request: Request):"""AI insights – called by backend mlService.getAIInsights()"""body = await request.json()query = body.get("query", "")context = body.get("context", {})result = await run_in_threadpool(reasoning_service.analyze, query, context)return {"insights": result.get("response", ""),5 unmodified lines@api.post("/api/models/predict")async def api_model_predict(request: Request):"""Model prediction – called by backend mlService.getModelPrediction()"""body = await request.json()model_type = body.get("model_type", "phishing_detection")input_data = body.get("input_data", {})result = ml_loader.predict(model_type, input_data)return result19 unmodified linesasync def api_v2_url_classify(request: Request):"""URL phishing/malware classification using elftsdmr/malware-url-detect (BERT).Body: { "url": "https://..." }"""body = await request.json()url = body.get("url", "").strip()if not url:return JSONResponse(status_code=400, content={"detail": "url required"})return transformer_loader.predict_url_phishing(url)3 unmodified linesasync def api_v2_dga_detect(request: Request):"""DGA-generated domain detection using YangYang-Research/dga-detection.Body: { "domain": "abc123xyz.com" }"""body = await request.json()domain = body.get("domain", "").strip()if not domain:return JSONResponse(status_code=400, content={"detail": "domain required"})return transformer_loader.predict_dga(domain)3 unmodified linesasync def api_v2_security_chat(request: Request):"""Cybersecurity Q&A, answered by the open-source model running in this Space.Body: { "query": "...", "max_tokens": 512 }"""body = await request.json()query = body.get("query", "").strip()if not query:return JSONResponse(status_code=400, content={"detail": "query required"})max_tokens = int(body.get("max_tokens", 512))result = await run_in_threadpool(transformer_loader.security_chat, query, max_tokens)# Last resort: ML heuristic if no LLM answeredif result.get("error"):20 unmodified lines{ "results": [ { ...same shape as /analyze-url... }, ... ], "total": N, "elapsed_ms": N }"""import timebody = await request.json()urls = body.get("urls", [])if not urls:return JSONResponse(status_code=400, content={"detail": "urls array required"})if len(urls) > 20:2 unmodified linest0 = time.time()results = []for url in urls:url = str(url).strip()if not url:results.append({"url": url, "error": "empty url"})continue69 unmodified lines{"url": "https://...", # optional"domain": "example.com", # optional"ip": "1.2.3.4", # optional"hash": "abc123...", # optional (future use)}Response: per-indicator results with unified risk summary."""body = await request.json()url = body.get("url", "").strip()domain = body.get("domain", "").strip()ioc_results: Dict[str, Any] = {}all_scores: List[float] = []18 unmodified lines# --- Domain analysis ---effective_domain = domainif not effective_domain and url:from urllib.parse import urlparse as _urlparseeffective_domain = _urlparse(url).hostname or ""if effective_domain:dga_result = transformer_loader.predict_dga(effective_domain)4 unmodified lines"dga_detection": dga_result,}# --- Overall risk summary ---overall_score = max(all_scores) if all_scores else 0.0if overall_score > 0.8:17 unmodified lines"overall_risk_level": risk_level,"overall_threat_score": round(overall_score, 3),"risk_score": round(overall_score * 100, 1),"indicators_analyzed": len(ioc_results),},"ai_analysis": ai_analysis,"timestamp": datetime.utcnow().isoformat(),8 unmodified linesBody: { "url": "https://..." }"""body = await request.json()url = body.get("url", "").strip()if not url:return JSONResponse(status_code=400, content={"detail": "url required"})9 unmodified linesbert_score = bert_result.get("threat_score", 0.0) if not bert_result.get("error") else None# DGA check on hostnamefrom urllib.parse import urlparse as _urlparsehostname = _urlparse(url).hostname or ""dga_result = transformer_loader.predict_dga(hostname) if hostname else Nonedga_score = dga_result.get("threat_score", 0.0) if dga_result and not dga_result.get("error") else 0.0105 unmodified lines"timestamp": "..."}"""body = await request.json()message = body.get("message", "").strip()session_id = body.get("session_id", "")history = body.get("conversation_history", [])context = body.get("context", {})if not message:return JSONResponse(status_code=400, content={"detail": "message required"})3 unmodified linessources: List[Dict] = []# System telemetrytelemetry = context.get("telemetry", {})if telemetry:cpu = telemetry.get("cpu", telemetry.get("cpu_percent"))ram = telemetry.get("ram", telemetry.get("ram_percent"))10 unmodified linessources.append({"type": "telemetry", "label": "System Telemetry", "value": ", ".join(telem_parts)})# Recent scan historyrecent_scans = context.get("recent_scans", [])if recent_scans:scan_summary = "; ".join(f"{s.get('url', 'unknown')} → {s.get('category', '?')} (score {s.get('risk_score', '?')}/100)"3 unmodified linessources.append({"type": "scan_history", "label": "Recent Scans", "value": f"{len(recent_scans)} scans"})# Active threatsactive_threats = context.get("active_threats", [])if active_threats:threat_summary = "; ".join(f"{t.get('type', '?')} [{t.get('severity', '?')}] from {t.get('source', '?')}"3 unmodified linessources.append({"type": "threats", "label": "Active Threats", "value": f"{len(active_threats)} active"})# Behavioral alertsbehavioral_alerts = context.get("behavioral_alerts", [])if behavioral_alerts:alert_summary = "; ".join(f"'{a.get('pattern', a.get('type', '?'))}' (score {a.get('score', '?')})"22 unmodified linesconversation_instruction = ""if history:conversation_instruction = "\n\nCONVERSATION CONTEXT (recent turns):\n" + "\n".join(f"{h.get('role','?').upper()}: {str(h.get('content',''))[:300]}"for h in history[-6:])85 unmodified lines@api.post("/api/analysis/network")async def api_analyze_network(request: Request):"""Network traffic analysis – called by backend mlService.analyzeNetworkTraffic()"""body = await request.json()traffic_data = body.get("traffic_data", {})result = await run_in_threadpool(reasoning_service.analyze,5 unmodified lines@api.post("/api/ai/execute-task")async def api_execute_task(request: Request):"""AI task execution – called by backend mlService.executeAITask()"""body = await request.json()task_type = body.get("task_type", "")task_data = body.get("task_data", {})result = await run_in_threadpool(reasoning_service.analyze,5 unmodified lines@api.post("/api/browser/analyze")async def api_analyze_browser(request: Request):"""Browser session analysis"""body = await request.json()session = body.get("session_data", body)result = await run_in_threadpool(reasoning_service.analyze,5 unmodified lines@api.post("/api/threat-feeds/analyze")async def api_analyze_threat_feed(request: Request):"""Threat feed analysis"""body = await request.json()result = await run_in_threadpool(reasoning_service.analyze,f"Analyze this threat feed:\n{json.dumps(body, indent=1)[:3000]}",3 unmodified lines@api.post("/api/datasets/process")async def api_process_dataset(request: Request):body = await request.json()return {"status": "processed","dataset_name": body.get("dataset_name", ""),93 unmodified lines949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170256 unmodified lines42742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249399 unmodified lines5935945955965975985996006016026036046056066076086096106116126136146156166176186191 unmodified line621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710218 unmodified lines92993093193293393493593693793893994094194294394494594694794894995095195231 unmodified lines984985986987988989990310 unmodified lines1301130213031304130513061307130813091310131124 unmodified lines133613371338133913401341134213431344134513464 unmodified lines1351135213531354135513561357135858 unmodified lines14171418141914201421142214232 unmodified lines1426142714281429143014311432143314345 unmodified lines14401441144214431444144514461447144819 unmodified lines146814691470147114721473147414753 unmodified lines147914801481148214831484148514863 unmodified lines1490149114921493149414951496149714981499150020 unmodified lines152115221523152415251526152715282 unmodified lines153115321533153415351536153715381539154069 unmodified lines1610161116121613161416151616161716181619162016211622162316241625162616271628162918 unmodified lines16481649165016511652165316544 unmodified lines1659166016611662166316641665166616671668166916701671167217 unmodified lines169016911692169316941695169616978 unmodified lines170617071708170917101711171217139 unmodified lines1723172417251726172717281729105 unmodified lines183518361837183818391840184118421843184418453 unmodified lines184918501851185218531854185510 unmodified lines18661867186818691870187118723 unmodified lines18761877187818791880188118823 unmodified lines188618871888188918901891189222 unmodified lines191519161917191819191920192185 unmodified lines20072008200920102011201220135 unmodified lines201920202021202220232024202520265 unmodified lines20322033203420352036203720385 unmodified lines20442045204620472048204920503 unmodified lines205420552056205720582059206093 unmodified lines]# ============================================================================# REQUEST INPUT# ============================================================================## What a caller sends is checked here, so a wrong body is answered with# HTTP 400 and a reason instead of an unhandled error (HTTP 500).class BadRequest(ValueError):"""Input the caller got wrong. Answered with HTTP 400 and this message."""async def json_object(request) -> Dict:"""The request body as a JSON object."""try:body = await request.json()except Exception:raise BadRequest("Request body must be valid JSON")if not isinstance(body, dict):raise BadRequest("Request body must be a JSON object")return bodydef text_field(body: Dict, name: str) -> str:"""A string field, stripped. A missing or null field is the empty string."""value = body.get(name)if value is None:return ""if not isinstance(value, str):raise BadRequest(f"'{name}' must be a string")return value.strip()def object_field(body: Dict, name: str) -> Dict:"""An object field. A missing or null field is an empty object."""value = body.get(name)if value is None:return {}if not isinstance(value, dict):raise BadRequest(f"'{name}' must be an object")return valuedef list_field(body: Dict, name: str) -> List:"""An array field. A missing or null field is an empty array."""value = body.get(name)if value is None:return []if not isinstance(value, list):raise BadRequest(f"'{name}' must be an array")return valuedef int_field(body: Dict, name: str, default: int, low: int, high: int) -> int:"""A whole-number field, limited to low..high. Missing or null is the default."""value = body.get(name)if value is None:return defaultif isinstance(value, bool):raise BadRequest(f"'{name}' must be a whole number")try:number = int(value)except (TypeError, ValueError, OverflowError):raise BadRequest(f"'{name}' must be a whole number")return max(low, min(high, number))def dicts_in(items: List) -> List[Dict]:"""The objects in a list; entries of any other type are dropped."""return [item for item in items if isinstance(item, dict)]# ============================================================================# REASONING SERVICE (LLM-backed analysis for the REST API)# ============================================================================256 unmodified linesself.ready = loaded > 0logger.info(f"ML Models: {loaded} loaded — {list(self.models.keys())}")# The features the models were trained on, in training order# (train_and_upload_models.py). Values are matched by name, never by position.FEATURE_ORDER = ["url_length", "hostname_length", "path_length", "is_https","has_ip_address", "has_suspicious_tld", "subdomain_count","has_port", "query_params_count", "has_at_symbol","has_double_slash", "special_char_count",]@classmethoddef feature_vector(cls, features: Dict) -> Tuple[List[float], List[str]]:"""The features as numbers in training order, and the names that werenot supplied (0 in the vector). Raises BadRequest for a value that isnot a finite number."""if not isinstance(features, dict):raise BadRequest("input_data must be an object of feature names and numbers")row, missing = [], []for name in cls.FEATURE_ORDER:value = features.get(name)if value is None:missing.append(name)row.append(0.0)continueif isinstance(value, bool):value = int(value)if not isinstance(value, (int, float)) or value != value or value in (float("inf"), float("-inf")):raise BadRequest(f"Feature '{name}' must be a number")row.append(float(value))return row, missing@staticmethoddef is_outlier_detector(model) -> bool:"""IsolationForest and the other scikit-learn outlier detectors: adecision margin around a fitted offset, and no class probabilities."""return (not hasattr(model, "predict_proba")and hasattr(model, "decision_function") and hasattr(model, "offset_"))def predict(self, model_name: str, features: Dict) -> Dict:row, missing = self.feature_vector(features)# A model is only asked about a complete feature set. With features# missing it would be scoring zeros it was never given, so the rule-based# estimate answers instead and says which features were absent.if model_name not in self.models or missing:result = self._heuristic_predict(model_name, features)if missing and model_name in self.models:result["missing_features"] = missingreturn resulttry:model = self.models[model_name]scaler = self.scalers.get(model_name)X = np.array([row])if scaler is not None:X = scaler.transform(X)if self.is_outlier_detector(model):return {"model": model_name,**anomaly_verdict(float(model.decision_function(X)[0])),"probabilities": {},"inference_source": "ml_model","timestamp": datetime.utcnow().isoformat(),}prediction = int(model.predict(X)[0])confidence = 0.5probabilities = {}99 unmodified lines}def anomaly_verdict(margin: float) -> Dict:"""Read an outlier detector's decision margin as a threat verdict.scikit-learn outlier detectors (the anomaly model is an IsolationForest)answer +1 for normal and -1 for an anomaly. Their decision margin ispositive for normal points, negative for anomalies and zero at the model'sown boundary. They have no class probabilities, so threat_score is thatmargin re-centred on 0.5: below 0.5 the model calls the input normal, aboveit anomalous. It is not a probability, and score_kind says so."""is_threat = margin < 0threat_score = min(1.0, max(0.0, 0.5 - margin))return {"prediction": 1 if is_threat else 0,"prediction_label": "threat" if is_threat else "benign","confidence": round(max(threat_score, 1.0 - threat_score), 4),"threat_score": round(threat_score, 4),"anomaly_margin": round(margin, 4),"score_kind": "anomaly_margin",}ml_loader = MLModelLoader()1 unmodified line# URL FEATURE EXTRACTION# ============================================================================def split_url(url: str) -> Dict:"""The parts of a URL that the features are built from. Never raises: textthat is not a well-formed URL (an unclosed "[" in the host, a port that isnot a number) still yields whatever could be read, because callers alsoscore URLs picked out of free text."""try:parsed = urlparse(url)parts = {"scheme": parsed.scheme, "hostname": parsed.hostname or "","path": parsed.path or "", "query": parsed.query or "",}except ValueError:scheme = url.split("://", 1)[0].lower() if "://" in url else ""return {"scheme": scheme, "hostname": "", "path": "", "query": "", "has_port": 0}try:parts["has_port"] = 1 if parsed.port else 0except ValueError:parts["has_port"] = 1 # a port is given, but it is not a valid numberreturn partsdef extract_url_features(url: str) -> Dict:parts = split_url(url)hostname = parts["hostname"]return {"url_length": len(url),"hostname_length": len(hostname),"path_length": len(parts["path"]),"is_https": 1 if parts["scheme"] == "https" else 0,"has_ip_address": 1 if all(p.isdigit() for p in hostname.split(".")) and len(hostname.split(".")) == 4 else 0,"has_suspicious_tld": 1 if any(hostname.endswith(t) for t in [".xyz", ".tk", ".ml", ".ga", ".cf", ".top", ".buzz"]) else 0,"subdomain_count": max(0, len(hostname.split(".")) - 2),"has_port": parts["has_port"],"query_params_count": len(parts["query"].split("&")) if parts["query"] else 0,"has_at_symbol": 1 if "@" in url else 0,"has_double_slash": 1 if "//" in parts["path"] else 0,"special_char_count": sum(1 for c in url if c in "!@#$%^&*()+={}[]|\\:;<>?,"),}def describe_ip(value: str) -> Dict:"""What can be said about an IP address without a reputation source: whetherit is an address at all, and what kind of range it is in. It is not scored."""import ipaddresstry:address = ipaddress.ip_address(value)except ValueError:return {"value": value, "valid": False, "status": "not_scored", "note": "Not a valid IPv4 or IPv6 address."}if address.is_loopback:scope = "loopback"elif address.is_link_local:scope = "link-local"elif address.is_multicast:scope = "multicast"elif address.is_private:scope = "private"elif address.is_reserved or address.is_unspecified:scope = "reserved"else:scope = "public"return {"value": str(address), "valid": True, "version": address.version, "scope": scope,"status": "not_scored","note": "This service has no IP reputation source, so the address is classified by range only.",}HASH_TYPES = {32: "md5", 40: "sha1", 64: "sha256", 128: "sha512"}def describe_hash(value: str) -> Dict:"""What can be said about a file hash without a reputation source: whichalgorithm its length matches. It is not scored."""digest = value.lower()is_hex = bool(digest) and all(c in "0123456789abcdef" for c in digest)hash_type = HASH_TYPES.get(len(digest)) if is_hex else Nonereturn {"value": digest, "valid": hash_type is not None, "hash_type": hash_type,"status": "not_scored","note": "This service has no file reputation source, so the hash is identified by length only."if hash_type else "Not an MD5, SHA-1, SHA-256 or SHA-512 hex digest.",}# ============================================================================# TRANSFORMER MODEL LOADER (Phase 3 — real HF transformer models)# ============================================================================218 unmodified linesdef predict_dga(self, domain: str) -> Dict:"""Detect DGA-generated domains using a Shannon-entropy + character-pattern heuristic.Real DGA domains have high entropy, low pronounceability, no real word substrings.Every label except the top-level one is scored and the mostgenerated-looking one is reported. The registered name is not always thefirst label ("www.<generated>.com"), and without a public-suffix list itcannot be picked out by position."""labels = [label for label in domain.lower().strip().split('.') if label]if not labels:return {"model": "dga_detector", "error": "empty domain"}candidates = labels[:-1] if len(labels) > 1 else labelsresult = max((self._score_dga_label(label[:60]) for label in candidates),key=lambda scored: scored["threat_score"])result["labels_scored"] = len(candidates)return result@staticmethoddef _score_dga_label(d: str) -> Dict:import math# Shannon entropy of character distributionfrom collections import Counterfreq = Counter(d)31 unmodified lines"is_threat": is_dga,"confidence": round(score * 100, 2) if is_dga else round((1 - score) * 100, 2),"threat_score": round(score, 4),"scored_label": d,"features": {"entropy": round(entropy, 3),"vowel_ratio": round(vowel_ratio, 3),310 unmodified lines)@api.exception_handler(BadRequest)async def bad_request(request: Request, error: BadRequest):return JSONResponse(status_code=400, content={"detail": str(error)})@api.get("/health")async def api_health():return {24 unmodified lines@api.post("/analyze")async def api_analyze(request: Request):"""Main analysis endpoint – called by backend mlService.chatWithAI()"""body = await json_object(request)query = text_field(body, "query")# The context is only serialised into the prompt, so any JSON value is fine.context = body.get("context")history = body.get("conversation_history")result = await run_in_threadpool(reasoning_service.analyze, query, context, history)return result4 unmodified linesReturns per-model predictions + unified aggregate with risk_score (0-100).All models now consistently include threat_score (probability of class-1)."""body = await json_object(request)url = text_field(body, "url")if not url:return JSONResponse(status_code=400, content={"detail": "URL required"})features = extract_url_features(url)58 unmodified lines@api.post("/scan-threats")async def api_scan_threats(request: Request):"""Threat scanning – called by backend mlService.scanForThreats()"""body = await json_object(request)query = json.dumps(body.get("data", body), indent=1)[:3000]result = await run_in_threadpool(reasoning_service.analyze, f"Scan these indicators for threats:\n{query}")return result2 unmodified lines@api.post("/api/insights/generate")async def api_generate_insights(request: Request):"""AI insights – called by backend mlService.getAIInsights()"""body = await json_object(request)query = text_field(body, "query")context = body.get("context")result = await run_in_threadpool(reasoning_service.analyze, query, context)return {"insights": result.get("response", ""),5 unmodified lines@api.post("/api/models/predict")async def api_model_predict(request: Request):"""Model prediction – called by backend mlService.getModelPrediction()"""body = await json_object(request)model_type = text_field(body, "model_type") or "phishing_detection"input_data = object_field(body, "input_data")result = ml_loader.predict(model_type, input_data)return result19 unmodified linesasync def api_v2_url_classify(request: Request):"""URL phishing/malware classification using elftsdmr/malware-url-detect (BERT).Body: { "url": "https://..." }"""body = await json_object(request)url = text_field(body, "url")if not url:return JSONResponse(status_code=400, content={"detail": "url required"})return transformer_loader.predict_url_phishing(url)3 unmodified linesasync def api_v2_dga_detect(request: Request):"""DGA-generated domain detection using YangYang-Research/dga-detection.Body: { "domain": "abc123xyz.com" }"""body = await json_object(request)domain = text_field(body, "domain")if not domain:return JSONResponse(status_code=400, content={"detail": "domain required"})return transformer_loader.predict_dga(domain)3 unmodified linesasync def api_v2_security_chat(request: Request):"""Cybersecurity Q&A, answered by the open-source model running in this Space.Body: { "query": "...", "max_tokens": 512 }"""body = await json_object(request)query = text_field(body, "query")if not query:return JSONResponse(status_code=400, content={"detail": "query required"})max_tokens = int_field(body, "max_tokens", 512, 1, 2048)result = await run_in_threadpool(transformer_loader.security_chat, query, max_tokens)# Last resort: ML heuristic if no LLM answeredif result.get("error"):20 unmodified lines{ "results": [ { ...same shape as /analyze-url... }, ... ], "total": N, "elapsed_ms": N }"""import timebody = await json_object(request)urls = list_field(body, "urls")if not urls:return JSONResponse(status_code=400, content={"detail": "urls array required"})if len(urls) > 20:2 unmodified linest0 = time.time()results = []for url in urls:if not isinstance(url, str):results.append({"url": url, "error": "url must be a string"})continueurl = url.strip()if not url:results.append({"url": url, "error": "empty url"})continue69 unmodified lines{"url": "https://...", # optional"domain": "example.com", # optional"ip": "1.2.3.4", # optional, described but not scored"hash": "abc123...", # optional, described but not scored}Response: per-indicator results with unified risk summary. The summary isbuilt from the URL and domain only: there is no reputation source here forIP addresses or file hashes, so they are reported under their own keys withstatus "not_scored" and listed in summary.indicators_not_scored."""body = await json_object(request)url = text_field(body, "url")domain = text_field(body, "domain")ip = text_field(body, "ip")file_hash = text_field(body, "hash")ioc_results: Dict[str, Any] = {}all_scores: List[float] = []18 unmodified lines# --- Domain analysis ---effective_domain = domainif not effective_domain and url:effective_domain = split_url(url)["hostname"]if effective_domain:dga_result = transformer_loader.predict_dga(effective_domain)4 unmodified lines"dga_detection": dga_result,}scored = len(ioc_results)# --- IP and hash: described, never scored ---if ip:ioc_results["ip"] = describe_ip(ip)if file_hash:ioc_results["hash"] = describe_hash(file_hash)# --- Overall risk summary ---overall_score = max(all_scores) if all_scores else 0.0if overall_score > 0.8:17 unmodified lines"overall_risk_level": risk_level,"overall_threat_score": round(overall_score, 3),"risk_score": round(overall_score * 100, 1),"indicators_analyzed": scored,"indicators_not_scored": [kind for kind in ("ip", "hash") if kind in ioc_results],},"ai_analysis": ai_analysis,"timestamp": datetime.utcnow().isoformat(),8 unmodified linesBody: { "url": "https://..." }"""body = await json_object(request)url = text_field(body, "url")if not url:return JSONResponse(status_code=400, content={"detail": "url required"})9 unmodified linesbert_score = bert_result.get("threat_score", 0.0) if not bert_result.get("error") else None# DGA check on hostnamehostname = split_url(url)["hostname"]dga_result = transformer_loader.predict_dga(hostname) if hostname else Nonedga_score = dga_result.get("threat_score", 0.0) if dga_result and not dga_result.get("error") else 0.0105 unmodified lines"timestamp": "..."}"""body = await json_object(request)message = text_field(body, "message")session_id = text_field(body, "session_id")history = dicts_in(list_field(body, "conversation_history"))context = object_field(body, "context")if not message:return JSONResponse(status_code=400, content={"detail": "message required"})3 unmodified linessources: List[Dict] = []# System telemetrytelemetry = object_field(context, "telemetry")if telemetry:cpu = telemetry.get("cpu", telemetry.get("cpu_percent"))ram = telemetry.get("ram", telemetry.get("ram_percent"))10 unmodified linessources.append({"type": "telemetry", "label": "System Telemetry", "value": ", ".join(telem_parts)})# Recent scan historyrecent_scans = dicts_in(list_field(context, "recent_scans"))if recent_scans:scan_summary = "; ".join(f"{s.get('url', 'unknown')} → {s.get('category', '?')} (score {s.get('risk_score', '?')}/100)"3 unmodified linessources.append({"type": "scan_history", "label": "Recent Scans", "value": f"{len(recent_scans)} scans"})# Active threatsactive_threats = dicts_in(list_field(context, "active_threats"))if active_threats:threat_summary = "; ".join(f"{t.get('type', '?')} [{t.get('severity', '?')}] from {t.get('source', '?')}"3 unmodified linessources.append({"type": "threats", "label": "Active Threats", "value": f"{len(active_threats)} active"})# Behavioral alertsbehavioral_alerts = dicts_in(list_field(context, "behavioral_alerts"))if behavioral_alerts:alert_summary = "; ".join(f"'{a.get('pattern', a.get('type', '?'))}' (score {a.get('score', '?')})"22 unmodified linesconversation_instruction = ""if history:conversation_instruction = "\n\nCONVERSATION CONTEXT (recent turns):\n" + "\n".join(f"{str(h.get('role') or '?').upper()}: {str(h.get('content',''))[:300]}"for h in history[-6:])85 unmodified lines@api.post("/api/analysis/network")async def api_analyze_network(request: Request):"""Network traffic analysis – called by backend mlService.analyzeNetworkTraffic()"""body = await json_object(request)traffic_data = body.get("traffic_data", {})result = await run_in_threadpool(reasoning_service.analyze,5 unmodified lines@api.post("/api/ai/execute-task")async def api_execute_task(request: Request):"""AI task execution – called by backend mlService.executeAITask()"""body = await json_object(request)task_type = text_field(body, "task_type")task_data = body.get("task_data", {})result = await run_in_threadpool(reasoning_service.analyze,5 unmodified lines@api.post("/api/browser/analyze")async def api_analyze_browser(request: Request):"""Browser session analysis"""body = await json_object(request)session = body.get("session_data", body)result = await run_in_threadpool(reasoning_service.analyze,5 unmodified lines@api.post("/api/threat-feeds/analyze")async def api_analyze_threat_feed(request: Request):"""Threat feed analysis"""body = await json_object(request)result = await run_in_threadpool(reasoning_service.analyze,f"Analyze this threat feed:\n{json.dumps(body, indent=1)[:3000]}",3 unmodified lines@api.post("/api/datasets/process")async def api_process_dataset(request: Request):body = await json_object(request)return {"status": "processed","dataset_name": body.get("dataset_name", ""),
app.py+311-67