import os import spaces import torch import gradio as gr from mmdsys_model import MODEL_PATH, load_model, classify # On a ZeroGPU Space torch reports CUDA at startup, so the model can be loaded # straight onto it. On a normal CPU Space this falls back to "cpu". DEVICE = "cuda" if torch.cuda.is_available() else "cpu" model = None load_error = None if os.path.exists(MODEL_PATH): try: model = load_model(MODEL_PATH, DEVICE) except Exception as e: # wrong architecture, corrupt file, etc. load_error = f"Could not load {MODEL_PATH}: {e}" else: load_error = f"{MODEL_PATH} not found. Upload your trained weights to the root of this Space." @spaces.GPU(duration=10) def run_model(text): """Runs on a GPU when one is attached (ZeroGPU); a harmless no-op decorator otherwise.""" return classify(model, text, DEVICE) def predict(text): if model is None: raise gr.Error(load_error) if not text or not text.strip(): return None, None, "" severity, types = run_model(text) verdict = max(severity, key=severity.get) if types: top = max(types, key=types.get) summary = f"BAD: {top} ({types[top]:.0%})" else: summary = verdict.upper() return severity, types, summary EXAMPLES = [ "Thanks so much, that was really helpful!", "The meeting is at 3pm in room 204.", "nobody likes you, just disappear", "Congratulations!! You won a free iPhone, click this link now", "I'm going to hurt you, watch your back", "I need to kill the process that's hanging on the server", ] with gr.Blocks(title="MMDSYS") as demo: gr.Markdown("# 🛡️ MMDSYS\n**Message Moderation Detection SYStem**: good, neutral or bad, " "and if bad, what type.") if load_error: gr.Markdown(f"⚠️ {load_error}") inp = gr.Textbox(label="Message", lines=3, placeholder="Type a message to check...") btn = gr.Button("Check message", variant="primary") verdict = gr.Textbox(label="Verdict", interactive=False) with gr.Row(): sev_out = gr.Label(label="Severity", num_top_classes=3) type_out = gr.Label(label="Type of bad (only shown when bad)", num_top_classes=6) gr.Examples(EXAMPLES, inputs=inp) btn.click(predict, inp, [sev_out, type_out, verdict]) inp.submit(predict, inp, [sev_out, type_out, verdict]) if __name__ == "__main__": demo.launch()