dira-api / app.py
rathath's picture
Upload 3 files
26e3c0b verified
Raw History Blame Contribute Delete
8.82 kB
"""
DIR'A AI service for a Hugging Face Space (Gradio SDK).
It only runs models and fetches public comments. It does NOT touch the
database (Spaces block the MySQL port): the PHP site on Railway calls these
endpoints and saves the results itself.
Gradio API (every call is two steps):
POST /gradio_api/call/<name> {"data": [...]} -> {"event_id": "..."}
GET /gradio_api/call/<name>/<event_id> -> "event: complete\ndata: [ {...} ]"
predict [comment, api_key]
one comment -> its 5 behavior labels (used when a player writes a comment)
spam [text, api_key]
a complaint -> probability that it is an advert / scam (Model 2)
analyze_game [steam_app_id, game_name, catalog_json, refresh_youtube, api_key]
fetches Steam reviews + YouTube comments for one game and runs the model
on all of them -> how many comments showed each behavior
Secrets (Space settings):
API_KEY shared secret with the website (same value as AI_API_KEY on Railway)
YOUTUBE_API_KEY YouTube Data API key, used by analyze_game
HF_TOKEN only if the model repo is private
"""
import spaces # must be imported before torch on ZeroGPU Spaces
import json
import os
import re
import threading
import time
import gradio as gr
import requests
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from youtube_comments import YouTubeError, fetch_youtube_comments, merge_unique
MODEL_PATH = os.getenv("MODEL_PATH", "rathath/dira-toxicity-model")
SPAM_MODEL = os.getenv("SPAM_MODEL", "mshenoda/roberta-spam")
HF_TOKEN = os.getenv("HF_TOKEN") # only needed if the model repo is private
API_KEY = os.getenv("API_KEY") # shared secret with the Railway site
THRESHOLD = 0.5
BATCH_SIZE = 16
MAX_STEAM_REVIEWS = 100
LABELS = ["threat", "bullying", "sexual_harassment", "hate_speech", "other_toxicity"]
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, token=HF_TOKEN)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH, token=HF_TOKEN)
model.eval()
def allowed(api_key):
return not API_KEY or api_key == API_KEY
# =========================
# CLEANING (same rules as py/process_all_games.py)
# =========================
def clean_comment(text):
if not text:
return ""
text = re.sub(r"https?://\S+|www\.\S+", "", str(text), flags=re.IGNORECASE)
return re.sub(r"\s+", " ", text).strip()
def is_valid_comment(text):
text = clean_comment(text)
if not text or len(text) < 20 or len(text.split()) < 3:
return False
return bool(re.search(r"[A-Za-z]", text))
# =========================
# MODEL 1: toxicity labels
# =========================
# LABEL_0 = is_toxic (not used), 1..5 = the behaviors in LABELS order
def label_batch(texts):
inputs = tokenizer(texts, return_tensors="pt", truncation=True, padding=True, max_length=256)
with torch.no_grad():
outputs = model(**inputs)
return (torch.sigmoid(outputs.logits).numpy() >= THRESHOLD).astype(int)
def count_labels(comments):
counts = {k: 0 for k in LABELS}
for i in range(0, len(comments), BATCH_SIZE):
preds = label_batch(comments[i:i + BATCH_SIZE])
for j, key in enumerate(LABELS, start=1):
counts[key] += int(preds[:, j].sum())
return counts
def predict(comment, api_key="", request: gr.Request = None):
if not allowed(api_key):
return {"success": False, "message": "Unauthorized."}
cleaned = clean_comment(comment)
if not is_valid_comment(cleaned):
return {"success": False, "message": "Invalid comment."}
preds = label_batch([cleaned])[0]
return {"success": True, "prediction": {key: int(preds[j]) for j, key in enumerate(LABELS, start=1)}}
# =========================
# MODEL 2: spam / scam complaints
# =========================
# Pretrained RoBERTa spam classifier (MIT licence): label 1 = spam.
# Loaded on the first request so the Space starts as fast as before.
spam_lock = threading.Lock()
spam_parts = {}
def spam(text, api_key="", request: gr.Request = None):
if not allowed(api_key):
return {"success": False, "message": "Unauthorized."}
text = str(text or "").strip()[:1000]
if not text:
return {"success": False, "message": "Missing text."}
with spam_lock:
if not spam_parts:
spam_parts["tok"] = AutoTokenizer.from_pretrained(SPAM_MODEL)
spam_parts["model"] = AutoModelForSequenceClassification.from_pretrained(SPAM_MODEL)
spam_parts["model"].eval()
inputs = spam_parts["tok"]([text], return_tensors="pt", truncation=True, padding=True, max_length=256)
with torch.no_grad():
logits = spam_parts["model"](**inputs).logits
probs = torch.softmax(logits, dim=-1)[0]
p = float(probs[1]) if probs.shape[0] > 1 else float(torch.sigmoid(logits[0][0]))
return {"success": True, "spam_probability": round(p, 4), "is_spam": p >= 0.5}
# =========================
# ANALYZE ONE GAME (admin "Analyze" button)
# =========================
def fetch_steam_reviews(steam_app_id, max_reviews=MAX_STEAM_REVIEWS):
reviews, cursor = [], "*"
while len(reviews) < max_reviews:
try:
data = requests.get(
f"https://store.steampowered.com/appreviews/{steam_app_id}",
params={"json": 1, "filter": "recent", "language": "english",
"num_per_page": min(100, max_reviews - len(reviews)), "cursor": cursor},
timeout=20,
).json()
except Exception:
break
if not data or not data.get("success") or not data.get("reviews"):
break
for review in data["reviews"]:
text = clean_comment(review.get("review") or "")
if is_valid_comment(text):
reviews.append(text)
if len(reviews) >= max_reviews:
break
new_cursor = data.get("cursor")
if not new_cursor or new_cursor == cursor:
break
cursor = new_cursor
time.sleep(0.3)
return reviews
def analyze_game(steam_app_id, game_name, catalog_json="[]", refresh_youtube=False,
api_key="", request: gr.Request = None):
if not allowed(api_key):
return {"success": False, "message": "Unauthorized."}
game_name = str(game_name or "").strip()
if not game_name:
return {"success": False, "message": "Missing game name."}
try:
catalog = [str(n) for n in json.loads(catalog_json or "[]") if n]
except ValueError:
catalog = []
if game_name not in catalog:
catalog.append(game_name)
steam = fetch_steam_reviews(str(steam_app_id).strip()) if str(steam_app_id or "").strip() else []
try:
youtube = fetch_youtube_comments(game_name, catalog, clean_comment, is_valid_comment,
refresh=bool(refresh_youtube))
except YouTubeError as error:
# same rule as before: without YouTube the old score is kept
return {"success": True, "skipped": True, "message": str(error)}
comments = merge_unique(steam + youtube, clean_comment, is_valid_comment)
counts = count_labels(comments) if comments else {k: 0 for k in LABELS}
return {
"success": True,
"skipped": False,
"comments_count": len(comments),
"steam": len(steam),
"youtube": len(youtube),
"counts": counts,
}
# ZeroGPU refuses to start unless at least one @spaces.GPU function exists.
# The models are small enough for CPU, so this is never called.
@spaces.GPU
def _gpu_placeholder():
return None
with gr.Blocks(title="DIR'A AI API") as demo:
gr.Markdown("# DIR'A AI API\nUsed by the Dir'a website. Each tab is also an API endpoint.")
key = gr.Textbox(label="API key", type="password")
with gr.Tab("Comment"):
c_in = gr.Textbox(label="Comment")
c_out = gr.JSON(label="Result")
gr.Button("Analyze comment").click(predict, [c_in, key], c_out, api_name="predict")
with gr.Tab("Spam check"):
s_in = gr.Textbox(label="Complaint text")
s_out = gr.JSON(label="Result")
gr.Button("Check").click(spam, [s_in, key], s_out, api_name="spam")
with gr.Tab("Analyze game"):
g_app = gr.Textbox(label="Steam app id")
g_name = gr.Textbox(label="Game name")
g_cat = gr.Textbox(label="Other game names (JSON list)", value="[]")
g_ref = gr.Checkbox(label="Ignore this month's YouTube cache", value=False)
g_out = gr.JSON(label="Result")
gr.Button("Analyze game").click(analyze_game, [g_app, g_name, g_cat, g_ref, key], g_out,
api_name="analyze_game")
demo.queue(default_concurrency_limit=2)
demo.launch()