File size: 12,875 Bytes
833aed9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"""
Business logic for moderation and guardrail services
"""

import json
import os
import uuid
import asyncio
from datetime import datetime
from typing import Dict, List, Tuple, Optional

import openai
import gspread
from google.oauth2 import service_account

# Import from parent directory
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
from utils import MODEL_CONFIGS, predict_with_model

# --- Categories ---
CATEGORIES = {
    "binary": ["binary"],
    "hateful": ["hateful_l1", "hateful_l2"],
    "insults": ["insults"],
    "sexual": ["sexual_l1", "sexual_l2"],
    "physical_violence": ["physical_violence"],
    "self_harm": ["self_harm_l1", "self_harm_l2"],
    "all_other_misconduct": ["all_other_misconduct_l1", "all_other_misconduct_l2"],
}

# --- OpenAI Setup ---
client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
async_client = openai.AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# --- Google Sheets Config ---
GOOGLE_SHEET_URL = os.environ.get("GOOGLE_SHEET_URL")
GOOGLE_CREDENTIALS = os.environ.get("GCP_SERVICE_ACCOUNT")
RESULTS_SHEET_NAME = "results"
VOTES_SHEET_NAME = "votes"
CHATBOT_SHEET_NAME = "chatbot"


def get_gspread_client():
    """Get authenticated Google Sheets client"""
    credentials = service_account.Credentials.from_service_account_info(
        json.loads(GOOGLE_CREDENTIALS),
        scopes=[
            "https://www.googleapis.com/auth/spreadsheets",
            "https://www.googleapis.com/auth/drive",
        ],
    )
    return gspread.authorize(credentials)


def save_results_data(row: Dict):
    """Save moderation results to Google Sheets"""
    try:
        gc = get_gspread_client()
        sheet = gc.open_by_url(GOOGLE_SHEET_URL)
        ws = sheet.worksheet(RESULTS_SHEET_NAME)
        ws.append_row(list(row.values()))
    except Exception as e:
        print(f"Error saving results data: {e}")


def save_vote_data(text_id: str, agree: bool):
    """Save user feedback vote to Google Sheets"""
    try:
        gc = get_gspread_client()
        sheet = gc.open_by_url(GOOGLE_SHEET_URL)
        ws = sheet.worksheet(VOTES_SHEET_NAME)
        vote_row = {
            "datetime": datetime.now().isoformat(),
            "text_id": text_id,
            "agree": agree
        }
        ws.append_row(list(vote_row.values()))
    except Exception as e:
        print(f"Error saving vote data: {e}")


def log_chatbot_data(row: Dict):
    """Log chatbot interaction to Google Sheets"""
    try:
        gc = get_gspread_client()
        sheet = gc.open_by_url(GOOGLE_SHEET_URL)
        ws = sheet.worksheet(CHATBOT_SHEET_NAME)
        ws.append_row([
            row["datetime"], row["text_id"], row["text"], row["binary_score"],
            row["hateful_l1_score"], row["hateful_l2_score"], row["insults_score"],
            row["sexual_l1_score"], row["sexual_l2_score"], row["physical_violence_score"],
            row["self_harm_l1_score"], row["self_harm_l2_score"], row["aom_l1_score"],
            row["aom_l2_score"], row["openai_score"]
        ])
    except Exception as e:
        print(f"Error saving chatbot data: {e}")


# --- Moderation Logic ---

def analyze_text(text: str, model_key: str = None) -> Dict:
    """
    Analyze text for moderation risks
    Returns dict with binary score, categories, text_id, and model info
    """
    if not text.strip():
        return {
            "binary_score": 0.0,
            "binary_verdict": "pass",
            "binary_percentage": 0,
            "categories": [],
            "text_id": "",
            "model_used": model_key or "lionguard-2.1"
        }
    
    try:
        text_id = str(uuid.uuid4())
        results, selected_model_key = predict_with_model([text], model_key)
        binary_score = results.get('binary', [0.0])[0]
        
        # Determine verdict
        if binary_score < 0.4:
            verdict = "pass"
        elif 0.4 <= binary_score < 0.7:
            verdict = "warn"
        else:
            verdict = "fail"
        
        # Process categories
        main_categories = ['hateful', 'insults', 'sexual', 'physical_violence', 'self_harm', 'all_other_misconduct']
        category_emojis = {
            'hateful': '🀬',
            'insults': 'πŸ’’',
            'sexual': 'πŸ”ž',
            'physical_violence': 'βš”οΈ',
            'self_harm': '☹️',
            'all_other_misconduct': 'πŸ™…β€β™€οΈ'
        }
        
        categories_list = []
        max_scores = {}
        
        for category in main_categories:
            subcategories = CATEGORIES[category]
            level_scores = [results.get(subcategory_key, [0.0])[0] for subcategory_key in subcategories]
            max_score = max(level_scores) if level_scores else 0.0
            max_scores[category] = max_score
            
            category_name = category.replace('_', ' ').title()
            categories_list.append({
                "name": category_name,
                "emoji": category_emojis.get(category, 'πŸ“'),
                "max_score": max_score
            })
        
        # Save to Google Sheets if enabled
        if GOOGLE_SHEET_URL and GOOGLE_CREDENTIALS:
            results_row = {
                "datetime": datetime.now().isoformat(),
                "text_id": text_id,
                "text": text,
                "binary_score": binary_score,
                "model": selected_model_key,
            }
            for category in main_categories:
                results_row[f"{category}_max"] = max_scores[category]
            save_results_data(results_row)
        
        return {
            "binary_score": binary_score,
            "binary_verdict": verdict,
            "binary_percentage": int(binary_score * 100),
            "categories": categories_list,
            "text_id": text_id,
            "model_used": selected_model_key
        }
    
    except Exception as e:
        print(f"Error analyzing text: {e}")
        raise


def submit_feedback(text_id: str, agree: bool) -> Dict:
    """Submit user feedback"""
    if not text_id:
        return {"success": False, "message": "No text ID provided"}
    
    if GOOGLE_SHEET_URL and GOOGLE_CREDENTIALS:
        save_vote_data(text_id, agree)
        message = "πŸŽ‰ Thank you!" if agree else "πŸ“ Thanks for the feedback!"
        return {"success": True, "message": message}
    
    return {"success": False, "message": "Voting not available"}


# --- Guardrail Comparison Logic (Async) ---

async def get_openai_response_async(message: str, system_prompt: str = "You are a helpful assistant.") -> str:
    """Get OpenAI chat response asynchronously"""
    try:
        response = await async_client.chat.completions.create(
            model="gpt-4.1-nano",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": message}
            ],
            max_tokens=500,
            temperature=0,
            seed=42,
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"Error: {str(e)}. Please check your OpenAI API key."


async def openai_moderation_async(message: str) -> bool:
    """Check if message is flagged by OpenAI moderation"""
    try:
        response = await async_client.moderations.create(input=message)
        return response.results[0].flagged
    except Exception as e:
        print(f"Error in OpenAI moderation: {e}")
        return False


def lionguard_2_sync(message: str, model_key: str, threshold: float = 0.5) -> Tuple[bool, float]:
    """Check if message is flagged by Lionguard"""
    try:
        results, _ = predict_with_model([message], model_key)
        binary_prob = results.get('binary', [0.0])[0]
        return binary_prob > threshold, binary_prob
    except Exception as e:
        print(f"Error in LionGuard inference for {model_key}: {e}")
        return False, 0.0


async def process_no_moderation(message: str, history: List[Dict]) -> List[Dict]:
    """Process message without moderation"""
    no_mod_response = await get_openai_response_async(message)
    history.append({"role": "user", "content": message})
    history.append({"role": "assistant", "content": no_mod_response})
    return history


async def process_openai_moderation(message: str, history: List[Dict]) -> List[Dict]:
    """Process message with OpenAI moderation"""
    openai_flagged = await openai_moderation_async(message)
    history.append({"role": "user", "content": message})
    if openai_flagged:
        openai_response = "🚫 This message has been flagged by OpenAI moderation"
        history.append({"role": "assistant", "content": openai_response})
    else:
        openai_response = await get_openai_response_async(message)
        history.append({"role": "assistant", "content": openai_response})
    return history


async def process_lionguard(message: str, history: List[Dict], model_key: str) -> Tuple[List[Dict], float]:
    """Process message with Lionguard model"""
    loop = asyncio.get_event_loop()
    lg_flagged, lg_score = await loop.run_in_executor(None, lionguard_2_sync, message, model_key, 0.5)
    
    history.append({"role": "user", "content": message})
    if lg_flagged:
        lg_response = f"🚫 This message has been flagged by {MODEL_CONFIGS[model_key]['label']}"
        history.append({"role": "assistant", "content": lg_response})
    else:
        lg_response = await get_openai_response_async(message)
        history.append({"role": "assistant", "content": lg_response})
    return history, lg_score


def _log_chatbot_sync(message: str, lg_score: float, model_key: str):
    """Sync helper for logging chatbot data"""
    try:
        results, selected_model_key = predict_with_model([message], model_key)
        now = datetime.now().isoformat()
        text_id = str(uuid.uuid4())
        row = {
            "datetime": now,
            "text_id": text_id,
            "text": message,
            "binary_score": results.get("binary", [None])[0],
            "hateful_l1_score": results.get(CATEGORIES['hateful'][0], [None])[0],
            "hateful_l2_score": results.get(CATEGORIES['hateful'][1], [None])[0],
            "insults_score": results.get(CATEGORIES['insults'][0], [None])[0],
            "sexual_l1_score": results.get(CATEGORIES['sexual'][0], [None])[0],
            "sexual_l2_score": results.get(CATEGORIES['sexual'][1], [None])[0],
            "physical_violence_score": results.get(CATEGORIES['physical_violence'][0], [None])[0],
            "self_harm_l1_score": results.get(CATEGORIES['self_harm'][0], [None])[0],
            "self_harm_l2_score": results.get(CATEGORIES['self_harm'][1], [None])[0],
            "aom_l1_score": results.get(CATEGORIES['all_other_misconduct'][0], [None])[0],
            "aom_l2_score": results.get(CATEGORIES['all_other_misconduct'][1], [None])[0],
            "openai_score": None,
        }
        try:
            openai_result = client.moderations.create(input=message)
            row["openai_score"] = float(openai_result.results[0].category_scores.get("hate", 0.0))
        except Exception:
            row["openai_score"] = None
        
        log_chatbot_data(row)
    except Exception as e:
        print(f"Error in sync logging: {e}")


async def process_chat_message(
    message: str,
    model_key: str,
    history_no_mod: List[Dict],
    history_openai: List[Dict],
    history_lg: List[Dict]
) -> Tuple[List[Dict], List[Dict], List[Dict], Optional[float]]:
    """
    Process message concurrently across all three guardrails
    Returns updated histories and LionGuard score
    """
    if not message.strip():
        return history_no_mod, history_openai, history_lg, None
    
    # Run all three processes concurrently
    results = await asyncio.gather(
        process_no_moderation(message, history_no_mod),
        process_openai_moderation(message, history_openai),
        process_lionguard(message, history_lg, model_key),
        return_exceptions=True
    )
    
    # Unpack results
    history_no_mod = results[0] if not isinstance(results[0], Exception) else history_no_mod
    history_openai = results[1] if not isinstance(results[1], Exception) else history_openai
    history_lg_result = results[2] if not isinstance(results[2], Exception) else (history_lg, 0.0)
    history_lg = history_lg_result[0]
    lg_score = history_lg_result[1] if isinstance(history_lg_result, tuple) else 0.0
    
    # Log to Google Sheets in background
    if GOOGLE_SHEET_URL and GOOGLE_CREDENTIALS:
        try:
            loop = asyncio.get_event_loop()
            loop.run_in_executor(None, _log_chatbot_sync, message, lg_score, model_key)
        except Exception as e:
            print(f"Chatbot logging failed: {e}")
    
    return history_no_mod, history_openai, history_lg, lg_score