Spaces:
Runtime error
Runtime error
Download app.py from Kleinpuki2/Gaurd: direct link, hf CLI and curl.
- Browser
- Download file 3.37 kB
-
https://huggingface.co/spaces/Kleinpuki2/Gaurd/resolve/main/app.py
- Command line
-
hf download hf://spaces/Kleinpuki2/Gaurd/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Kleinpuki2/Gaurd/resolve/main/app.py
3.37 kB
| import os | |
| import time | |
| import gradio as gr | |
| import torch | |
| import uvicorn | |
| from fastapi import FastAPI, Header, HTTPException | |
| from pydantic import BaseModel | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| from common import FLAG_LABELS, clean | |
| MODEL_ID = os.getenv("MODEL_ID", "Kleinpuki2/belidungen") | |
| HF_TOKEN = os.getenv("HF_TOKEN") or None | |
| API_KEY = os.getenv("API_KEY", "") | |
| PORT = int(os.getenv("PORT", "7860")) | |
| torch.set_num_threads(max(1, os.cpu_count() or 1)) | |
| print("Lade Modell...", flush=True) | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN) | |
| model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID, token=HF_TOKEN).eval() | |
| id2label = {int(k): v for k, v in model.config.id2label.items()} | |
| print("Modell geladen:", list(id2label.values()), flush=True) | |
| def predict(texts): | |
| texts = [clean(t) for t in texts] | |
| enc = tokenizer(texts, truncation=True, max_length=128, padding=True, return_tensors="pt") | |
| probs = torch.softmax(model(**enc).logits.float(), -1) | |
| out = [] | |
| for t, pr in zip(texts, probs): | |
| scores = {id2label[i]: round(float(v) * 100, 1) for i, v in enumerate(pr)} | |
| label = max(scores, key=scores.get) | |
| bad = round(sum(v for k, v in scores.items() if k in FLAG_LABELS), 1) | |
| out.append({"text": t, "label": label, "confidence": scores[label], "verstoss": bad, "flagged": label in FLAG_LABELS, "scores": scores}) | |
| return out | |
| api = FastAPI(title="botnixcore KI") | |
| class In(BaseModel): | |
| text: str | |
| class Many(BaseModel): | |
| texts: list[str] | |
| def check_key(k): | |
| if API_KEY and k != API_KEY: | |
| raise HTTPException(401, "Falscher Schlüssel") | |
| def health(): | |
| return {"ok": True, "labels": list(id2label.values())} | |
| def check(body: In, x_key: str = Header(default="")): | |
| check_key(x_key) | |
| if not body.text.strip(): | |
| raise HTTPException(400, "Text ist leer") | |
| t0 = time.perf_counter() | |
| r = predict([body.text[:1200]])[0] | |
| r["ms"] = round((time.perf_counter() - t0) * 1000, 1) | |
| return r | |
| def check_many(body: Many, x_key: str = Header(default="")): | |
| check_key(x_key) | |
| return predict([t[:1200] for t in body.texts[:64] if t.strip()] or ["."]) | |
| def ui(text): | |
| if not text or not text.strip(): | |
| return "Bitte einen Text eingeben.", {} | |
| r = predict([text])[0] | |
| head = f"{'🚫 VERSTOSS' if r['flagged'] else '✅ OK'} · {r['label']} ({r['confidence']} %) · Verstoß gesamt: {r['verstoss']} %" | |
| return head, {k: v / 100 for k, v in r["scores"].items()} | |
| with gr.Blocks(title="botnixcore KI") as demo: | |
| gr.Markdown("# 🛡️ botnixcore Beleidigungs-KI\nText eingeben und prüfen. API für den Bot: `POST /check`") | |
| inp = gr.Textbox(label="Nachricht", placeholder="z. B. du bist so ein lappen", lines=2) | |
| btn = gr.Button("Prüfen", variant="primary") | |
| out = gr.Markdown() | |
| bars = gr.Label(label="Wahrscheinlichkeiten", num_top_classes=6) | |
| btn.click(ui, inp, [out, bars]) | |
| inp.submit(ui, inp, [out, bars]) | |
| gr.Examples(["du hurensohn", "ich kill dich im 1v1", "ich weiß wo du wohnst", "scheiße mein wlan ist weg", "wer hat lust auf minecraft"], inp) | |
| app = gr.mount_gradio_app(api, demo, path="/") | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=PORT) | |