File size: 8,819 Bytes
e3e12e2
26e3c0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3e12e2
 
 
 
26e3c0b
e3e12e2
 
26e3c0b
 
e3e12e2
 
26e3c0b
e3e12e2
 
 
26e3c0b
 
e3e12e2
26e3c0b
e3e12e2
26e3c0b
e3e12e2
26e3c0b
 
 
e3e12e2
 
 
 
 
 
26e3c0b
 
 
 
 
 
 
 
e3e12e2
 
 
 
 
 
 
 
26e3c0b
e3e12e2
 
 
 
 
26e3c0b
 
 
 
e3e12e2
26e3c0b
 
e3e12e2
 
26e3c0b
e3e12e2
 
26e3c0b
 
 
 
 
 
 
e3e12e2
 
 
26e3c0b
e3e12e2
26e3c0b
 
e3e12e2
26e3c0b
 
 
e3e12e2
26e3c0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3e12e2
 
 
26e3c0b
e3e12e2
 
 
 
 
26e3c0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3e12e2
26e3c0b
e3e12e2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""
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()