Spaces:
Paused
Paused
Update the CyberForge ML service
Browse filesFiles changed (3)
- Dockerfile+3-5
- app.py+116-393
- requirements.txt+1-12
123420 unmodified lines2526272829303132331 unmodified line3536373839# Use Python 3.11 to avoid the gradio_client Python 3.13 bugFROM python:3.11-slimWORKDIR /app20 unmodified lines# Copy requirements and install dependenciesCOPY --chown=user requirements.txt .RUN pip install --no-cache-dir --upgrade pip && \pip install --no-cache-dir -r requirements.txt && \pip install --no-cache-dir ipykernel && \python -m ipykernel install --user --name python3 --display-name "Python 3"# Copy application codeCOPY --chown=user . .1 unmodified line# Expose portEXPOSE 7860# Run the application via uvicorn (FastAPI + Gradio mounted)CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123420 unmodified lines252627282930311 unmodified line3334353637# Python 3.11: the version this image has been built and run withFROM python:3.11-slimWORKDIR /app20 unmodified lines# Copy requirements and install dependenciesCOPY --chown=user requirements.txt .RUN pip install --no-cache-dir --upgrade pip && \pip install --no-cache-dir -r requirements.txt# Copy application codeCOPY --chown=user . .1 unmodified line# Expose portEXPOSE 7860# Run the API via uvicorn (FastAPI only, no web interface)CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
12345678910111213 unmodified lines2627282930313233343536372 unmodified lines404142434445468 unmodified lines5556575859606118 unmodified lines808182838485868788899091929394959697989910010110211 unmodified lines114115116117118119988 unmodified lines110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135495 unmodified lines1450145114521453145414551456740 unmodified lines2197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223433 unmodified lines234723482349235023512352235323542355"""CyberForge AI - ML Training & Inference PlatformHugging Face Spaces deployment with:1) Gradio UI for notebook execution, training, and inference2) FastAPI REST endpoints for the Heroku backend (mlService.js)"""import gradio as grimport pandas as pdimport numpy as npimport jsonimport os13 unmodified linesfrom url_features import (extract_url_features, popular_domains_loaded, rescale_score,set_popular_domains, split_url)# ML Librariesfrom sklearn.model_selection import train_test_split, cross_val_scorefrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, IsolationForestfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import StandardScaler, LabelEncoderfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, f1_scoreimport joblib# Hugging Face Hub2 unmodified lines# FastAPI for REST endpointsfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponsefrom starlette.concurrency import run_in_threadpoollogging.basicConfig(level=logging.INFO)8 unmodified linesMODELS_DIR.mkdir(exist_ok=True)DATASETS_DIR = APP_DIR / "datasets"DATASETS_DIR.mkdir(exist_ok=True)NOTEBOOKS_DIR = APP_DIR / "notebooks"KNOWLEDGE_BASE_DIR = APP_DIR / "knowledge_base"KNOWLEDGE_BASE_DIR.mkdir(exist_ok=True)TRAINING_DATA_DIR = APP_DIR / "training_data"18 unmodified linesLOCAL_LLM_QUEUE_TIMEOUT_S = float(os.environ.get("LOCAL_LLM_QUEUE_TIMEOUT_S", "5"))logger.info(f"APP_DIR: {APP_DIR}")logger.info(f"NOTEBOOKS_DIR: {NOTEBOOKS_DIR}")logger.info(f"NOTEBOOKS_DIR exists: {NOTEBOOKS_DIR.exists()}")# Model types available for trainingMODEL_TYPES = {"Random Forest": RandomForestClassifier,"Gradient Boosting": GradientBoostingClassifier,"Logistic Regression": LogisticRegression,"Isolation Forest (Anomaly)": IsolationForest,}SECURITY_TASKS = ["Malware Detection", "Phishing Detection", "Network Intrusion Detection","Anomaly Detection", "Botnet Detection", "Web Attack Detection","Spam Detection", "Vulnerability Assessment", "DNS Tunneling Detection","Cryptomining Detection",]# ============================================================================11 unmodified lines"""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):988 unmodified lines# ============================================================================# NOTEBOOK EXECUTION (existing Gradio functionality)# ============================================================================def get_available_notebooks() -> List[str]:if not NOTEBOOKS_DIR.exists():return []return sorted([f.name for f in NOTEBOOKS_DIR.glob("*.ipynb")])def read_notebook_content(notebook_name: str) -> str:"""Read and display notebook content as markdown"""notebook_path = NOTEBOOKS_DIR / notebook_nameif not notebook_path.exists():return f"Notebook not found: {notebook_name}"try:with open(notebook_path, "r") as f:nb = json.load(f)output = f"# {notebook_name}\n\n"for i, cell in enumerate(nb.get("cells", []), 1):cell_type = cell.get("cell_type", "code")source = "".join(cell.get("source", []))if cell_type == "markdown":output += f"{source}\n\n"else:output += f"### Cell {i} (Python)\n```python\n{source}\n```\n\n"return outputexcept Exception as e:return f"Error reading notebook: {str(e)}"def execute_notebook(notebook_name: str, progress=gr.Progress()) -> Tuple[str, str]:"""Execute a notebook and return output"""notebook_path = NOTEBOOKS_DIR / notebook_nameoutput_path = NOTEBOOKS_DIR / f"output_{notebook_name}"if not notebook_path.exists():available = list(NOTEBOOKS_DIR.glob("*.ipynb")) if NOTEBOOKS_DIR.exists() else []return f"Error: Notebook not found: {notebook_path}\nAvailable: {available}", ""progress(0.1, desc="Starting notebook execution...")try:cmd = [sys.executable, "-m", "nbconvert","--to", "notebook", "--execute","--output", str(output_path.absolute()),"--ExecutePreprocessor.timeout=600","--ExecutePreprocessor.kernel_name=python3",str(notebook_path.absolute()),]progress(0.3, desc="Executing cells...")result = subprocess.run(cmd, capture_output=True, text=True, cwd=str(NOTEBOOKS_DIR), timeout=900)progress(0.8, desc="Processing output...")if result.returncode == 0:if output_path.exists():with open(output_path, "r") as f:executed_nb = json.load(f)outputs = []for i, cell in enumerate(executed_nb.get("cells", []), 1):if cell.get("cell_type") == "code":for out in cell.get("outputs", []):if "text" in out:outputs.append(f"Cell {i}:\n{''.join(out['text'])}")elif "data" in out and "text/plain" in out["data"]:outputs.append(f"Cell {i}:\n{''.join(out['data']['text/plain'])}")progress(1.0, desc="Complete!")return "Notebook executed successfully!", "\n\n".join(outputs)else:return "Notebook executed but output file not found", result.stdoutelse:return f"Execution failed:\n{result.stderr}", result.stdoutexcept subprocess.TimeoutExpired:return "Error: Notebook execution timed out (15 min limit)", ""except Exception as e:return f"Error executing notebook: {str(e)}", ""def run_notebook_cell(notebook_name: str, cell_number: int) -> str:"""Execute a single cell from a notebook"""notebook_path = NOTEBOOKS_DIR / notebook_nameif not notebook_path.exists():return f"Error: Notebook not found at {notebook_path}"try:original_cwd = os.getcwd()os.chdir(NOTEBOOKS_DIR)with open(notebook_path, "r") as f:nb = json.load(f)cells = [c for c in nb.get("cells", []) if c.get("cell_type") == "code"]if cell_number < 1 or cell_number > len(cells):os.chdir(original_cwd)return f"Error: Cell {cell_number} not found. Available: 1-{len(cells)}"cell = cells[int(cell_number) - 1]source = "".join(cell.get("source", []))import iofrom contextlib import redirect_stdout, redirect_stderrnamespace = {"__name__": "__main__", "__file__": str(notebook_path)}stdout_capture = io.StringIO()stderr_capture = io.StringIO()with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):try:exec(source, namespace)except Exception as e:os.chdir(original_cwd)return f"Error: {str(e)}"os.chdir(original_cwd)output = stdout_capture.getvalue()errors = stderr_capture.getvalue()result_text = f"### Cell {int(cell_number)} Output:\n"if output:result_text += f"```\n{output}\n```\n"if errors:result_text += f"\n**Warnings/Errors:**\n```\n{errors}\n```"if not output and not errors:result_text += "*(No output)*"return result_textexcept Exception as e:try:os.chdir(original_cwd)except Exception:passreturn f"Error: {str(e)}"# ============================================================================# MODEL TRAINING (existing Gradio functionality)# ============================================================================class SecurityModelTrainer:def __init__(self):self.scaler = StandardScaler()self.label_encoder = LabelEncoder()def prepare_data(self, df: pd.DataFrame, target_col: str = "label") -> Tuple:if target_col not in df.columns:raise ValueError(f"Target column '{target_col}' not found")X = df.drop(columns=[target_col])y = df[target_col]X = X.select_dtypes(include=[np.number]).fillna(0)if y.dtype == "object":y = self.label_encoder.fit_transform(y)X_scaled = self.scaler.fit_transform(X)return train_test_split(X_scaled, y, test_size=0.2, random_state=42)def train_model(self, model_type: str, X_train, y_train):if model_type not in MODEL_TYPES:raise ValueError(f"Unknown model type: {model_type}")model_class = MODEL_TYPES[model_type]if model_type == "Isolation Forest (Anomaly)":model = model_class(contamination=0.1, random_state=42)else:model = model_class(random_state=42)model.fit(X_train, y_train)return modeldef evaluate_model(self, model, X_test, y_test) -> Dict:y_pred = model.predict(X_test)return {"accuracy": accuracy_score(y_test, y_pred),"f1_score": f1_score(y_test, y_pred, average="weighted", zero_division=0),}trainer = SecurityModelTrainer()def train_model_from_data(data_file, model_type: str, task: str, progress=gr.Progress()):"""Train model from uploaded data"""if data_file is None:return "Please upload a CSV file", None, Noneprogress(0.1, desc="Loading data...")try:df = pd.read_csv(data_file.name)progress(0.3, desc="Preparing data...")X_train, X_test, y_train, y_test = trainer.prepare_data(df)progress(0.5, desc=f"Training {model_type}...")model = trainer.train_model(model_type, X_train, y_train)progress(0.8, desc="Evaluating model...")metrics = trainer.evaluate_model(model, X_test, y_test)model_name = f"{task.lower().replace(' ', '_')}_{model_type.lower().replace(' ', '_')}"model_path = MODELS_DIR / f"{model_name}.pkl"joblib.dump(model, model_path)progress(1.0, desc="Complete!")result = f"""## Training Complete!**Task:** {task}**Model:** {model_type}**Samples:** {len(df)}### Metrics- Accuracy: {metrics['accuracy']:.4f}- F1 Score: {metrics['f1_score']:.4f}**Model saved to:** {model_path}"""return result, str(model_path), json.dumps(metrics, indent=2)except Exception as e:return f"Error: {str(e)}", None, Nonedef run_inference(model_file, features_text: str):"""Run inference with a trained model"""if model_file is None:return "Please upload a model file"try:model = joblib.load(model_file.name)features = json.loads(features_text)X = np.array([list(features.values())])prediction = model.predict(X)[0]result = {"prediction": int(prediction), "features_used": len(features)}if hasattr(model, "predict_proba"):proba = model.predict_proba(X)[0]result["confidence"] = float(max(proba))result["probabilities"] = {str(i): float(p) for i, p in enumerate(proba)}return json.dumps(result, indent=2)except Exception as e:return f"Error: {str(e)}"def list_trained_models():models = list(MODELS_DIR.glob("*.pkl"))if not models:return "No trained models found"output = "## Trained Models\n\n"for model_path in models:size_kb = model_path.stat().st_size / 1024output += f"- **{model_path.name}** ({size_kb:.1f} KB)\n"return output# ============================================================================# FASTAPI APP (REST endpoints for Heroku backend mlService.js)# ============================================================================api = FastAPI(title="CyberForge AI API", version="1.0.0")api.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)@api.exception_handler(BadRequest)95 unmodified lines"popular_domains_loaded": popular_domains_loaded(),"transformers": transformer_loader.transformers_available,"transformer_models_loaded": list(transformer_loader.pipelines.keys()),"gradio_ui": True,},"version": "2.0.0","new_endpoints": [740 unmodified lines# ============================================================================# GRADIO INTERFACE (UI tabs – notebooks, training, inference, models, API)# ============================================================================def create_interface():with gr.Blocks(title="CyberForge AI") as demo:gr.Markdown("""# 🔐 CyberForge AI - ML Training PlatformTrain cybersecurity ML models and run Jupyter notebooks on Hugging Face.""")with gr.Tabs():# ============ NOTEBOOKS TAB ============with gr.TabItem("📓 Notebooks"):gr.Markdown("### Run ML Pipeline Notebooks\nExecute the CyberForge ML notebooks directly in the cloud.")with gr.Row():with gr.Column(scale=1):notebook_dropdown = gr.Dropdown(choices=get_available_notebooks(),label="Select Notebook",value=get_available_notebooks()[0] if get_available_notebooks() else None,)refresh_btn = gr.Button("🔄 Refresh List")view_btn = gr.Button("👁 View Content", variant="secondary")execute_btn = gr.Button("▶ Execute Notebook", variant="primary")gr.Markdown("### Run Single Cell")cell_number = gr.Number(label="Cell Number", value=1, minimum=1)run_cell_btn = gr.Button("Run Cell")with gr.Column(scale=2):notebook_status = gr.Markdown("Select a notebook to view or execute.")notebook_output = gr.Markdown("", label="Output")def refresh_notebooks():notebooks = get_available_notebooks()return gr.update(choices=notebooks, value=notebooks[0] if notebooks else None)refresh_btn.click(refresh_notebooks, outputs=notebook_dropdown)view_btn.click(read_notebook_content, inputs=notebook_dropdown, outputs=notebook_output)execute_btn.click(execute_notebook, inputs=notebook_dropdown, outputs=[notebook_status, notebook_output])run_cell_btn.click(run_notebook_cell, inputs=[notebook_dropdown, cell_number], outputs=notebook_output)# ============ TRAIN MODEL TAB ============with gr.TabItem("🎯 Train Model"):gr.Markdown("### Train a Security ML Model\nUpload your dataset and train a model for threat detection.")with gr.Row():with gr.Column():task_dropdown = gr.Dropdown(choices=SECURITY_TASKS, label="Security Task", value="Phishing Detection")model_dropdown = gr.Dropdown(choices=list(MODEL_TYPES.keys()), label="Model Type", value="Random Forest")data_upload = gr.File(label="Upload Training Data (CSV)", file_types=[".csv"])train_btn = gr.Button("🚀 Train Model", variant="primary")with gr.Column():train_output = gr.Markdown("Upload data and click Train to begin.")model_path_output = gr.Textbox(label="Model Path", visible=False)metrics_output = gr.Textbox(label="Metrics JSON", visible=False)train_btn.click(train_model_from_data, inputs=[data_upload, model_dropdown, task_dropdown], outputs=[train_output, model_path_output, metrics_output])# ============ INFERENCE TAB ============with gr.TabItem("🔍 Inference"):gr.Markdown("### Run Model Inference\nLoad a trained model and make predictions.")with gr.Row():with gr.Column():model_upload = gr.File(label="Upload Model (.pkl)")features_input = gr.Textbox(label="Features (JSON)", value='{"url_length": 50, "has_https": 1, "digit_count": 5}', lines=5)predict_btn = gr.Button("🎯 Predict", variant="primary")with gr.Column():prediction_output = gr.Textbox(label="Prediction Result", lines=10)predict_btn.click(run_inference, inputs=[model_upload, features_input], outputs=prediction_output)# ============ MODELS TAB ============with gr.TabItem("📦 Models"):gr.Markdown("### Trained Models")models_list = gr.Markdown(list_trained_models())refresh_models_btn = gr.Button("🔄 Refresh")refresh_models_btn.click(list_trained_models, outputs=models_list)# ============ API TAB ============with gr.TabItem("🔌 API"):gr.Markdown("""## API Integration — v2.0### Core Endpoints (stable, used by Heroku backend)| Method | Endpoint | Description ||--------|----------|-------------|| GET | `/health` | Health check — version, models, services || POST | `/analyze` | AI chat / general analysis (LLM or ML fallback) || POST | `/analyze-url` | URL threat analysis — 4 ML models + risk factors || POST | `/scan-threats` | Deep threat scan (LLM or ML fallback) || POST | `/api/insights/generate` | AI-generated security insights || POST | `/api/models/predict` | Direct ML model prediction || GET | `/models` | List loaded models with source info |### v2 Endpoints (new — for distributed agents + AI Deep Scan)| Method | Endpoint | Description ||--------|----------|-------------|| POST | `/api/v2/batch-analyze` | Batch analyze up to 20 URLs (for multi-agent) || GET | `/api/v2/explain/{model_name}` | Feature importances / explainability || POST | `/api/v2/url-classify` | BERT-based URL phishing classifier || POST | `/api/v2/dga-detect` | DGA domain detection (entropy heuristic) || POST | `/api/v2/ioc-scan` | Multi-IOC scanner: URL + domain + DGA + BERT || POST | `/api/v2/url-enrich` | Enriched analysis: ML + BERT + DGA + explainability || POST | `/api/v2/chat` | Security chatbot — context-grounded, RAG-lite, machine→human translation || POST | `/api/v2/security-chat` | Security LLM Q&A (open-source model running in this Space) || GET | `/api/v2/status` | Transformer model load status |### Quick Examples```bash# Batch analyze URLs (for distributed agents)curl -X POST https://che237-cyberforge.hf.space/api/v2/batch-analyze \\-H "Content-Type: application/json" \\-d '{"urls": ["https://example.com", "http://evil.xyz/login?id=1"]}'# Enriched URL analysis (Deep Scan mode)curl -X POST https://che237-cyberforge.hf.space/api/v2/url-enrich \\-H "Content-Type: application/json" \\-d '{"url": "https://example.com"}'# Feature explainabilitycurl https://che237-cyberforge.hf.space/api/v2/explain/phishing_detection# IOC multi-field scancurl -X POST https://che237-cyberforge.hf.space/api/v2/ioc-scan \\-H "Content-Type: application/json" \\-d '{"url": "http://192.168.1.1/login", "domain": "192.168.1.1"}'# Chatbot (Wave 2 extension point)curl -X POST https://che237-cyberforge.hf.space/api/v2/chat \\-H "Content-Type: application/json" \\-d '{"message": "Is this URL suspicious: http://login.g00gle.com.xyz/verify"}'```""")gr.Markdown("---\n**CyberForge AI** | [GitHub](https://github.com/Che237/cyberforge) | [Datasets](https://huggingface.co/datasets/Che237/cyberforge-datasets)")return demo# ============================================================================# MAIN – Mount Gradio on FastAPI# ============================================================================# Initialize services at startup3 unmodified linesthreading.Thread(target=local_llm.load, name="local-llm-loader", daemon=True).start()logger.info("✅ Services initialized")# Create Gradio app and mount it on FastAPIdemo = create_interface()app = gr.mount_gradio_app(api, demo, path="/")if __name__ == "__main__":import uvicorn1234567891011121313 unmodified lines27282930313233342 unmodified lines373839404142438 unmodified lines52535455565718 unmodified lines7677787980818283848586878889909111 unmodified lines103104105106107108109110111988 unmodified lines11001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119595 unmodified lines12911292129312941295129612971298740 unmodified lines2039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720683 unmodified lines2072207320742075207620772078"""CyberForge AI - ML inference serviceHugging Face Spaces deployment: FastAPI REST endpoints for the CyberForgebackend. Every route except / and /health needs the service key(ML_SERVICE_KEY), which only the backend holds; the two training routes needthe Space owner's Hugging Face token instead. Nothing here runs uploaded code,notebooks or uploaded models."""import hmacimport numpy as npimport jsonimport os13 unmodified linesfrom url_features import (extract_url_features, popular_domains_loaded, rescale_score,set_popular_domains, split_url)# Models are loaded only from the model repository (ml_loader below), never# from a caller: loading a joblib/pickle file can run code.import joblib# Hugging Face Hub2 unmodified lines# FastAPI for REST endpointsfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponsefrom starlette.concurrency import run_in_threadpoollogging.basicConfig(level=logging.INFO)8 unmodified linesMODELS_DIR.mkdir(exist_ok=True)DATASETS_DIR = APP_DIR / "datasets"DATASETS_DIR.mkdir(exist_ok=True)KNOWLEDGE_BASE_DIR = APP_DIR / "knowledge_base"KNOWLEDGE_BASE_DIR.mkdir(exist_ok=True)TRAINING_DATA_DIR = APP_DIR / "training_data"18 unmodified linesLOCAL_LLM_QUEUE_TIMEOUT_S = float(os.environ.get("LOCAL_LLM_QUEUE_TIMEOUT_S", "5"))logger.info(f"APP_DIR: {APP_DIR}")# Calls to every route except / and /health must carry this key in the# X-CyberForge-Service-Key header. It is a Space secret; the backend holds the# same value. Without it set, those routes answer 503 rather than run open.ML_SERVICE_KEY = os.environ.get("ML_SERVICE_KEY", "").strip()SERVICE_KEY_HEADER = "x-cyberforge-service-key"# The largest request body accepted, in bytes. Larger ones get HTTP 413.ML_MAX_BODY_BYTES = int(os.environ.get("ML_MAX_BODY_BYTES", str(256 * 1024)))logger.info(f"APP_DIR: {APP_DIR}")logger.info(f"Service key {'set' if ML_SERVICE_KEY else 'NOT set: inference routes will answer 503'}")# ============================================================================11 unmodified lines"""The request body as a JSON object."""try:body = await request.json()except BodyTooLarge:# Raised by ServiceGate while the body streams in; it answers 413.raiseexcept Exception:raise BadRequest("Request body must be valid JSON")if not isinstance(body, dict):988 unmodified lines# ============================================================================# FASTAPI APP (REST endpoints for Heroku backend mlService.js)# ============================================================================api = FastAPI(title="CyberForge AI API", version="1.0.0")api.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)PUBLIC_PATHS = {"/", "/health"}# These check the owner's Hugging Face token themselves (owner_token below).OWNER_PATHS = {"/api/admin/train", "/api/admin/train/status"}class BodyTooLarge(Exception):passdef service_key_valid(presented: Optional[bytes]) -> bool:if not ML_SERVICE_KEY or not presented:return Falsereturn hmac.compare_digest(presented, ML_SERVICE_KEY.encode("utf-8"))async def _reply(send, status: int, detail: str, code: str):body = json.dumps({"detail": detail, "code": code}).encode("utf-8")await send({"type": "http.response.start", "status": status,"headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]})await send({"type": "http.response.body", "body": body})class ServiceGate:"""Outermost middleware. It refuses a call without the service key beforeany route runs, and a body over ML_MAX_BODY_BYTES whether or not it statesits length."""def __init__(self, app):self.app = appasync def __call__(self, scope, receive, send):if scope["type"] != "http":return await self.app(scope, receive, send)path = scope.get("path", "")headers = dict(scope.get("headers") or [])# A CORS preflight carries no credentials; the CORS middleware answers it.if scope.get("method") != "OPTIONS" and path not in PUBLIC_PATHS and path not in OWNER_PATHS:if not ML_SERVICE_KEY:return await _reply(send, 503, "This service has no service key configured", "SERVICE_KEY_NOT_CONFIGURED")if not service_key_valid(headers.get(SERVICE_KEY_HEADER.encode())):return await _reply(send, 401, "A valid service key is required", "SERVICE_KEY_REQUIRED")stated = headers.get(b"content-length")if stated is not None:try:if int(stated) > ML_MAX_BODY_BYTES:return await _reply(send, 413, f"Request body is over {ML_MAX_BODY_BYTES} bytes", "BODY_TOO_LARGE")except ValueError:return await _reply(send, 400, "Content-Length must be a number", "BAD_CONTENT_LENGTH")received = 0started = Falseasync def bounded_receive():nonlocal receivedmessage = await receive()if message["type"] == "http.request":received += len(message.get("body", b""))if received > ML_MAX_BODY_BYTES:raise BodyTooLarge()return messageasync def tracked_send(message):nonlocal startedif message["type"] == "http.response.start":started = Trueawait send(message)try:await self.app(scope, bounded_receive, tracked_send)except BodyTooLarge:if started:raiseawait _reply(send, 413, f"Request body is over {ML_MAX_BODY_BYTES} bytes", "BODY_TOO_LARGE")# Added last, so it runs first: before CORS and every route.api.add_middleware(ServiceGate)@api.exception_handler(BadRequest)95 unmodified lines"popular_domains_loaded": popular_domains_loaded(),"transformers": transformer_loader.transformers_available,"transformer_models_loaded": list(transformer_loader.pipelines.keys()),"service_key": "required" if ML_SERVICE_KEY else "not_configured","max_body_bytes": ML_MAX_BODY_BYTES,},"version": "2.0.0","new_endpoints": [740 unmodified lines# ============================================================================# LANDING PAGE (static; the service has no interactive UI)# ============================================================================LANDING_HTML = """<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>CyberForge ML service</title><style>body{font-family:system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;line-height:1.5;color:#1b1f24;background:#fff}code{background:#f1f3f5;padding:0 .25rem;border-radius:3px}</style></head><body><h1>CyberForge ML service</h1><p>This Space serves the detection models and the security chat model to the CyberForge backend.It has no interactive interface: it does not run notebooks, train on uploaded data, or load uploaded models.</p><p><code>GET /health</code> is public. Every other route needs the service key held by the backend,and model training needs the Space owner's token.</p><p>Source: <a href="https://github.com/Che237/cyberforge">github.com/Che237/cyberforge</a></p></body></html>"""@api.get("/", response_class=HTMLResponse)async def landing():return LANDING_HTML# ============================================================================# MAIN# ============================================================================# Initialize services at startup3 unmodified linesthreading.Thread(target=local_llm.load, name="local-llm-loader", daemon=True).start()logger.info("✅ Services initialized")app = apiif __name__ == "__main__":import uvicorn
123458 unmodified lines14151617181920212212 unmodified lines3536373839404142434445464748# CyberForge AI - HuggingFace Space# Combined Gradio UI + FastAPI REST API# Core ML# Pinned: the .pkl files in Che237/cyberforge-models were saved with 1.8.0 and the8 unmodified linestransformers>=4.40.0tokenizers>=0.19.0# Gradio UIgradio>=5.20.0# FastAPI REST endpoints (for Heroku backend)fastapi>=0.100.0uvicorn[standard]>=0.22.012 unmodified lines--only-binary llama-cpp-pythonllama-cpp-python==0.3.36# Notebook executionnbformat>=5.10.0nbconvert>=7.16.0nest_asyncio>=1.6.0# HTTP client for notebookshttpx>=0.27.0# Data handlingdatasets>=2.20.0pyarrow>=17.0.0123458 unmodified lines14151617181912 unmodified lines323334353637# CyberForge AI - HuggingFace Space# FastAPI REST API only. There is no Gradio UI and no notebook runner (V2-ML01).# Core ML# Pinned: the .pkl files in Che237/cyberforge-models were saved with 1.8.0 and the8 unmodified linestransformers>=4.40.0tokenizers>=0.19.0# FastAPI REST endpoints (for Heroku backend)fastapi>=0.100.0uvicorn[standard]>=0.22.012 unmodified lines--only-binary llama-cpp-pythonllama-cpp-python==0.3.36# Data handlingdatasets>=2.20.0pyarrow>=17.0.0
Dockerfile+3-5
app.py+116-393
requirements.txt+1-12