Spaces:
Sleeping
Sleeping
File size: 67,653 Bytes
54ba978 eaee42c 87f60ba cb79076 688f230 87f60ba 688f230 87f60ba cb79076 87f60ba 688f230 87f60ba 478bcd0 cb79076 87f60ba |
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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 |
import os
import time
import threading
import torch
import base64
import io
import uuid
import requests
import numpy as np
from typing import List, Dict, Any, Optional, Union
from fastapi import FastAPI, HTTPException, Depends, Request, File, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, Field
from dotenv import load_dotenv
from huggingface_hub import snapshot_download
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
from detoxify import Detoxify
from PIL import Image
from tensorflow.keras.models import load_model
import uvicorn
from datetime import datetime, timedelta
from collections import defaultdict, deque
import tiktoken
load_dotenv()
os.makedirs("templates", exist_ok=True)
os.makedirs("static", exist_ok=True)
MODEL_REPO = "daniel-dona/gemma-3-270m-it"
LOCAL_DIR = os.path.join(os.getcwd(), "local_model")
os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
os.environ.setdefault("OMP_NUM_THREADS", str(os.cpu_count() or 2))
os.environ.setdefault("MKL_NUM_THREADS", os.environ["OMP_NUM_THREADS"])
os.environ.setdefault("OMP_PROC_BIND", "TRUE")
torch.set_num_threads(int(os.environ["OMP_NUM_THREADS"]))
torch.set_num_interop_threads(1)
torch.set_float32_matmul_precision("high")
app = FastAPI(title="AI Content Moderator API", description="Advanced content moderation API powered by AI")
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
def ensure_local_model(repo_id: str, local_dir: str, tries: int = 3, sleep_s: float = 3.0) -> str:
os.makedirs(local_dir, exist_ok=True)
for i in range(tries):
try:
snapshot_download(
repo_id=repo_id,
local_dir=local_dir,
local_dir_use_symlinks=False,
resume_download=True,
allow_patterns=["*.json", "*.model", "*.safetensors", "*.bin", "*.txt", "*.py"]
)
return local_dir
except Exception:
if i == tries - 1:
raise
time.sleep(sleep_s * (2 ** i))
return local_dir
print("Loading models...")
model_path = ensure_local_model(MODEL_REPO, LOCAL_DIR)
tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)
gemma_chat_template_simplified = (
"{% for message in messages %}"
"{% if message['role'] == 'user' %}"
"{{ '<start_of_turn>user\\n' + message['content'] | trim + '<end_of_turn>\\n' }}"
"{% elif message['role'] == 'assistant' %}"
"{{ '<start_of_turn>model\\n' + message['content'] | trim + '<end_of_turn>\\n' }}"
"{% endif %}"
"{% endfor %}"
"{% if add_generation_prompt %}"
"{{ '<start_of_turn>model\\n' }}"
"{% endif %}"
)
if tokenizer.chat_template is None:
tokenizer.chat_template = gemma_chat_template_simplified
model = AutoModelForCausalLM.from_pretrained(
model_path,
local_files_only=True,
torch_dtype=torch.float32,
device_map=None
)
model.eval()
detoxify_model = Detoxify('multilingual')
teachable_machine_url = "https://teachablemachine.withgoogle.com/models/gJOADmf_u/"
model_url = teachable_machine_url + "model.json"
weights_url = teachable_machine_url + "weights.bin"
model_path = os.path.join(os.getcwd(), "teachable_machine_model")
os.makedirs(model_path, exist_ok=True)
if not os.path.exists(os.path.join(model_path, "model.json")):
response = requests.get(model_url)
with open(os.path.join(model_path, "model.json"), "wb") as f:
f.write(response.content)
if not os.path.exists(os.path.join(model_path, "weights.bin")):
response = requests.get(weights_url)
with open(os.path.join(model_path, "weights.bin"), "wb") as f:
f.write(response.content)
image_model = load_model(model_path)
MODERATION_SYSTEM_PROMPT = (
"You are a multilingual content moderation classifier. "
"You MUST respond with exactly one lowercase letter: 's' for safe, 'u' for unsafe. "
"No explanations, no punctuation, no extra words. "
"If the message contains hate speech, harassment, sexual content involving minors, "
"extreme violence, self-harm encouragement, or other unsafe material, respond 'u'. "
"Otherwise respond 's'."
)
request_durations = deque(maxlen=100)
request_timestamps = deque(maxlen=1000)
daily_requests = defaultdict(int)
daily_tokens = defaultdict(int)
concurrent_requests = 0
concurrent_requests_lock = threading.Lock()
encoding = tiktoken.get_encoding("cl100k_base")
def count_tokens(text):
return len(encoding.encode(text))
def track_request_metrics(start_time, tokens_count):
end_time = time.time()
duration = end_time - start_time
request_durations.append(duration)
request_timestamps.append(datetime.now())
today = datetime.now().strftime("%Y-%m-%d")
daily_requests[today] += 1
daily_tokens[today] += tokens_count
def get_performance_metrics():
global concurrent_requests
with concurrent_requests_lock:
current_concurrent = concurrent_requests
if not request_durations:
avg_request_time = 0
peak_request_time = 0
else:
avg_request_time = sum(request_durations) / len(request_durations)
peak_request_time = max(request_durations)
now = datetime.now()
one_minute_ago = now - timedelta(seconds=60)
requests_last_minute = sum(1 for ts in request_timestamps if ts > one_minute_ago)
today = now.strftime("%Y-%m-%d")
today_requests = daily_requests.get(today, 0)
today_tokens = daily_tokens.get(today, 0)
last_7_days = []
for i in range(7):
date = (now - timedelta(days=i)).strftime("%Y-%m-%d")
last_7_days.append({
"date": date,
"requests": daily_requests.get(date, 0),
"tokens": daily_tokens.get(date, 0)
})
return {
"avg_request_time_ms": avg_request_time * 1000,
"peak_request_time_ms": peak_request_time * 1000,
"requests_per_minute": requests_last_minute,
"concurrent_requests": current_concurrent,
"today_requests": today_requests,
"today_tokens": today_tokens,
"last_7_days": last_7_days
}
class TextContent(BaseModel):
type: str = Field("text", description="Type of content")
text: str = Field(..., description="Text content")
class ImageContent(BaseModel):
type: str = Field("image", description="Type of content")
url: Optional[str] = Field(None, description="URL of the image")
base64: Optional[str] = Field(None, description="Base64 encoded image")
class ModerationRequest(BaseModel):
input: Union[str, List[Union[str, TextContent, ImageContent]]] = Field(..., description="Content to moderate")
model: Optional[str] = Field("multimodal-moderator", description="Model to use for moderation")
class ModerationResponse(BaseModel):
id: str
object: str
created: int
model: str
results: List[Dict[str, Any]]
def build_prompt(message, max_ctx_tokens=128):
full_user_message = f"{MODERATION_SYSTEM_PROMPT}\n\nUser input: '{message}'"
messages = [{"role": "user", "content": full_user_message}]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
while len(tokenizer(text, add_special_tokens=False).input_ids) > max_ctx_tokens and len(full_user_message) > 100:
full_user_message = full_user_message[:-50]
messages[0]['content'] = full_user_message
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
return text
def enforce_s_u(text: str) -> str:
text_lower = text.strip().lower()
if "u" in text_lower and "s" not in text_lower:
return "u"
if "unsafe" in text_lower:
return "u"
return "s"
def classify_text_with_gemma(message, max_tokens=3, temperature=0.1, top_p=0.95):
if not message.strip():
return {
"classification": "s",
"label": "SAFE",
"description": "Content appears to be safe and appropriate.",
"tokens_per_second": 0,
"processing_time": 0
}
text = build_prompt(message)
inputs = tokenizer([text], return_tensors="pt").to(model.device)
do_sample = bool(temperature and temperature > 0.0)
gen_kwargs = dict(
max_new_tokens=max_tokens,
do_sample=do_sample,
top_p=top_p,
temperature=temperature if do_sample else None,
use_cache=True,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id
)
try:
streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True, skip_prompt=True)
except TypeError:
streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
thread = threading.Thread(
target=model.generate,
kwargs={**inputs, **{k: v for k, v in gen_kwargs.items() if v is not None}, "streamer": streamer}
)
partial_text = ""
token_count = 0
start_time = None
with torch.inference_mode():
thread.start()
try:
for chunk in streamer:
if start_time is None:
start_time = time.time()
partial_text += chunk
token_count += 1
finally:
thread.join()
final_label = enforce_s_u(partial_text)
end_time = time.time() if start_time else time.time()
duration = max(1e-6, end_time - start_time)
tps = token_count / duration if duration > 0 else 0.0
if final_label == "s":
label = "SAFE"
description = "Content appears to be safe and appropriate."
else:
label = "UNSAFE"
description = "Content may contain inappropriate or harmful material."
return {
"classification": final_label,
"label": label,
"description": description,
"tokens_per_second": tps,
"processing_time": duration
}
def classify_text_with_detoxify(text):
predictions = detoxify_model.predict([text])
single_prediction = {key: value[0] for key, value in predictions.items()}
category_keys = [
"toxicity", "severe_toxicity", "obscene", "threat",
"insult", "identity_attack", "sexual_explicit"
]
scores = {}
for key in category_keys:
scores[key] = float(single_prediction.get(key, 0.0))
threshold = 0.5
bool_categories = {key: (scores[key] > threshold) for key in category_keys}
flagged = any(bool_categories.values())
return {
"flagged": flagged,
"categories": bool_categories,
"category_scores": scores
}
def classify_image(image_data):
try:
img = Image.open(io.BytesIO(image_data)).convert("RGB")
img = img.resize((224, 224))
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
predictions = image_model.predict(img_array)
class_idx = np.argmax(predictions[0])
classes = ["nothing", "nsfw"]
class_name = classes[class_idx]
confidence = float(predictions[0][class_idx])
return {
"classification": "u" if class_name == "nsfw" else "s",
"label": "NSFW" if class_name == "nsfw" else "SFW",
"description": "Content may contain inappropriate or harmful material." if class_name == "nsfw" else "Content appears to be safe and appropriate.",
"confidence": confidence,
"nsfw_score": confidence if class_name == "nsfw" else 1.0 - confidence
}
except Exception as e:
return {
"classification": "s",
"label": "ERROR",
"description": f"Error processing image: {str(e)}",
"confidence": 0.0,
"nsfw_score": 0.0
}
def process_content_item(item):
if isinstance(item, str):
gemma_result = classify_text_with_gemma(item)
detoxify_result = classify_text_with_detoxify(item)
flagged = gemma_result["classification"] == "u" or detoxify_result["flagged"]
return {
"flagged": flagged,
"categories": {
"hate": flagged,
"hate/threatening": flagged,
"harassment": flagged,
"harassment/threatening": flagged,
"self-harm": flagged,
"self-harm/intent": flagged,
"self-harm/instructions": flagged,
"sexual": flagged,
"sexual/minors": flagged,
"violence": flagged,
"violence/graphic": flagged,
"nsfw": detoxify_result["categories"].get("sexual_explicit", False)
},
"category_scores": {
"hate": 0.9 if flagged else 0.1,
"hate/threatening": 0.9 if flagged else 0.1,
"harassment": 0.9 if flagged else 0.1,
"harassment/threatening": 0.9 if flagged else 0.1,
"self-harm": 0.9 if flagged else 0.1,
"self-harm/intent": 0.9 if flagged else 0.1,
"self-harm/instructions": 0.9 if flagged else 0.1,
"sexual": detoxify_result["category_scores"].get("sexual_explicit", 0.1),
"sexual/minors": detoxify_result["category_scores"].get("sexual_explicit", 0.1) * 0.9,
"violence": 0.9 if flagged else 0.1,
"violence/graphic": 0.9 if flagged else 0.1,
"nsfw": detoxify_result["category_scores"].get("sexual_explicit", 0.1)
},
"text": item
}
elif isinstance(item, dict):
if item.get("type") == "text":
gemma_result = classify_text_with_gemma(item.get("text", ""))
detoxify_result = classify_text_with_detoxify(item.get("text", ""))
flagged = gemma_result["classification"] == "u" or detoxify_result["flagged"]
return {
"flagged": flagged,
"categories": {
"hate": flagged,
"hate/threatening": flagged,
"harassment": flagged,
"harassment/threatening": flagged,
"self-harm": flagged,
"self-harm/intent": flagged,
"self-harm/instructions": flagged,
"sexual": flagged,
"sexual/minors": flagged,
"violence": flagged,
"violence/graphic": flagged,
"nsfw": detoxify_result["categories"].get("sexual_explicit", False)
},
"category_scores": {
"hate": 0.9 if flagged else 0.1,
"hate/threatening": 0.9 if flagged else 0.1,
"harassment": 0.9 if flagged else 0.1,
"harassment/threatening": 0.9 if flagged else 0.1,
"self-harm": 0.9 if flagged else 0.1,
"self-harm/intent": 0.9 if flagged else 0.1,
"self-harm/instructions": 0.9 if flagged else 0.1,
"sexual": detoxify_result["category_scores"].get("sexual_explicit", 0.1),
"sexual/minors": detoxify_result["category_scores"].get("sexual_explicit", 0.1) * 0.9,
"violence": 0.9 if flagged else 0.1,
"violence/graphic": 0.9 if flagged else 0.1,
"nsfw": detoxify_result["category_scores"].get("sexual_explicit", 0.1)
},
"text": item.get("text", "")
}
elif item.get("type") == "image":
image_data = None
if item.get("url"):
try:
response = requests.get(item.get("url"))
image_data = response.content
except Exception:
return {
"flagged": False,
"categories": {
"hate": False,
"hate/threatening": False,
"harassment": False,
"harassment/threatening": False,
"self-harm": False,
"self-harm/intent": False,
"self-harm/instructions": False,
"sexual": False,
"sexual/minors": False,
"violence": False,
"violence/graphic": False,
"nsfw": False
},
"category_scores": {
"hate": 0.1,
"hate/threatening": 0.1,
"harassment": 0.1,
"harassment/threatening": 0.1,
"self-harm": 0.1,
"self-harm/intent": 0.1,
"self-harm/instructions": 0.1,
"sexual": 0.1,
"sexual/minors": 0.1,
"violence": 0.1,
"violence/graphic": 0.1,
"nsfw": 0.1
},
"image_url": item.get("url")
}
elif item.get("base64"):
try:
if item.get("base64").startswith("data:image"):
base64_data = item.get("base64").split(",")[1]
else:
base64_data = item.get("base64")
image_data = base64.b64decode(base64_data)
except Exception:
return {
"flagged": False,
"categories": {
"hate": False,
"hate/threatening": False,
"harassment": False,
"harassment/threatening": False,
"self-harm": False,
"self-harm/intent": False,
"self-harm/instructions": False,
"sexual": False,
"sexual/minors": False,
"violence": False,
"violence/graphic": False,
"nsfw": False
},
"category_scores": {
"hate": 0.1,
"hate/threatening": 0.1,
"harassment": 0.1,
"harassment/threatening": 0.1,
"self-harm": 0.1,
"self-harm/intent": 0.1,
"self-harm/instructions": 0.1,
"sexual": 0.1,
"sexual/minors": 0.1,
"violence": 0.1,
"violence/graphic": 0.1,
"nsfw": 0.1
},
"image_base64": item.get("base64")[:50] + "..." if len(item.get("base64", "")) > 50 else item.get("base64", "")
}
if image_data:
image_result = classify_image(image_data)
flagged = image_result["classification"] == "u"
return {
"flagged": flagged,
"categories": {
"hate": False,
"hate/threatening": False,
"harassment": False,
"harassment/threatening": False,
"self-harm": False,
"self-harm/intent": False,
"self-harm/instructions": False,
"sexual": flagged,
"sexual/minors": flagged,
"violence": False,
"violence/graphic": False,
"nsfw": flagged
},
"category_scores": {
"hate": 0.1,
"hate/threatening": 0.1,
"harassment": 0.1,
"harassment/threatening": 0.1,
"self-harm": 0.1,
"self-harm/intent": 0.1,
"self-harm/instructions": 0.1,
"sexual": image_result["nsfw_score"],
"sexual/minors": image_result["nsfw_score"] * 0.9,
"violence": 0.1,
"violence/graphic": 0.1,
"nsfw": image_result["nsfw_score"]
},
"image_url": item.get("url"),
"image_base64": item.get("base64")[:50] + "..." if item.get("base64") and len(item.get("base64", "")) > 50 else item.get("base64", "")
}
return {
"flagged": False,
"categories": {
"hate": False,
"hate/threatening": False,
"harassment": False,
"harassment/threatening": False,
"self-harm": False,
"self-harm/intent": False,
"self-harm/instructions": False,
"sexual": False,
"sexual/minors": False,
"violence": False,
"violence/graphic": False,
"nsfw": False
},
"category_scores": {
"hate": 0.1,
"hate/threatening": 0.1,
"harassment": 0.1,
"harassment/threatening": 0.1,
"self-harm": 0.1,
"self-harm/intent": 0.1,
"self-harm/instructions": 0.1,
"sexual": 0.1,
"sexual/minors": 0.1,
"violence": 0.1,
"violence/graphic": 0.1,
"nsfw": 0.1
}
}
def get_api_key(request: Request):
api_key = request.headers.get("Authorization") or request.query_params.get("api_key")
if not api_key:
raise HTTPException(status_code=401, detail="API key required")
if api_key.startswith("Bearer "):
api_key = api_key[7:]
env_api_key = os.getenv("API_KEY")
if not env_api_key or api_key != env_api_key:
raise HTTPException(status_code=401, detail="Invalid API key")
return api_key
@app.get("/", response_class=HTMLResponse)
async def get_home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/v1/moderations", response_model=ModerationResponse)
async def moderate_content(
request: ModerationRequest,
api_key: str = Depends(get_api_key)
):
global concurrent_requests
with concurrent_requests_lock:
concurrent_requests += 1
start_time = time.time()
total_tokens = 0
try:
input_data = request.input
if isinstance(input_data, str):
items = [input_data]
total_tokens += count_tokens(input_data)
elif isinstance(input_data, list):
items = input_data
for item in items:
if isinstance(item, str):
total_tokens += count_tokens(item)
elif isinstance(item, dict) and item.get("type") == "text":
total_tokens += count_tokens(item.get("text", ""))
else:
raise HTTPException(status_code=400, detail="Invalid input format")
if len(items) > 10:
raise HTTPException(status_code=400, detail="Too many input items. Maximum 10 allowed.")
results = []
for item in items:
result = process_content_item(item)
results.append(result)
response_data = {
"id": f"modr_{uuid.uuid4().hex[:24]}",
"object": "moderation",
"created": int(time.time()),
"model": request.model,
"results": results
}
track_request_metrics(start_time, total_tokens)
return response_data
finally:
with concurrent_requests_lock:
concurrent_requests -= 1
@app.get("/v1/metrics")
async def get_metrics(api_key: str = Depends(get_api_key)):
return get_performance_metrics()
with open("templates/index.html", "w") as f:
f.write("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Content Moderator</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
@keyframes float {
0% { transform: translateY(0px); }
50% { transform: translateY(-10px); }
100% { transform: translateY(0px); }
}
@keyframes pulse-border {
0% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.7); }
70% { box-shadow: 0 0 0 10px rgba(99, 102, 241, 0); }
100% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0); }
}
.float-animation {
animation: float 3s ease-in-out infinite;
}
.pulse-border {
animation: pulse-border 2s infinite;
}
.gradient-bg {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.glass-effect {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.2);
}
.safe-gradient {
background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
}
.unsafe-gradient {
background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}
</style>
</head>
<body class="min-h-screen gradient-bg text-white">
<div class="container mx-auto px-4 py-8">
<header class="text-center mb-12">
<div class="inline-block p-4 rounded-full glass-effect float-animation mb-6">
<i class="fas fa-shield-alt text-5xl text-white"></i>
</div>
<h1 class="text-4xl md:text-5xl font-bold mb-4">AI Content Moderator</h1>
<p class="text-xl text-gray-200 max-w-2xl mx-auto">
Advanced, multilingual and multimodal content classification tool powered by AI
</p>
</header>
<main class="max-w-6xl mx-auto">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-12">
<div class="lg:col-span-1">
<div class="glass-effect p-6 rounded-xl h-full">
<h2 class="text-2xl font-bold mb-4 flex items-center">
<i class="fas fa-key mr-2"></i> API Configuration
</h2>
<div class="mb-4">
<label class="block text-sm font-medium mb-2">API Key</label>
<div class="relative">
<input type="password" id="apiKey" placeholder="Enter your API key"
class="w-full px-4 py-3 rounded-lg bg-white/10 border border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-400 text-white">
<button id="toggleApiKey" class="absolute right-3 top-3 text-gray-300 hover:text-white">
<i class="fas fa-eye"></i>
</button>
</div>
</div>
<div class="mb-4">
<label class="block text-sm font-medium mb-2">Model</label>
<select id="modelSelect" class="w-full px-4 py-3 rounded-lg bg-white/10 border border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-400 text-white">
<option value="multimodal-moderator" selected>Multimodal Moderator</option>
</select>
</div>
<div class="mt-6">
<h3 class="text-lg font-semibold mb-2">API Endpoints</h3>
<div class="bg-black/20 p-4 rounded-lg text-sm font-mono">
<div class="mb-2">POST /v1/moderations</div>
<div>GET /v1/metrics</div>
</div>
</div>
</div>
</div>
<div class="lg:col-span-2">
<div class="glass-effect p-6 rounded-xl">
<h2 class="text-2xl font-bold mb-4 flex items-center">
<i class="fas fa-check-circle mr-2"></i> Content Analysis
</h2>
<div class="flex border-b border-white/20 mb-6">
<button id="textTab" class="px-4 py-2 font-medium border-b-2 border-indigo-400 text-indigo-300 tab-active">
Text
</button>
<button id="imageTab" class="px-4 py-2 font-medium border-b-2 border-transparent text-gray-300 hover:text-white">
Image
</button>
<button id="mixedTab" class="px-4 py-2 font-medium border-b-2 border-transparent text-gray-300 hover:text-white">
Mixed Content
</button>
</div>
<div id="textContent" class="tab-content">
<div class="mb-6">
<label class="block text-sm font-medium mb-2">Text to Analyze</label>
<textarea id="textInput" rows="6" placeholder="Enter any text in any language for content moderation analysis..."
class="w-full px-4 py-3 rounded-lg bg-white/10 border border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-400 text-white resize-none"></textarea>
</div>
<div class="flex space-x-4">
<button id="analyzeTextBtn" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-6 rounded-lg transition duration-300 transform hover:scale-105 pulse-border">
<i class="fas fa-search mr-2"></i> Analyze Text
</button>
<button id="clearTextBtn" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-3 px-6 rounded-lg transition duration-300">
<i class="fas fa-trash mr-2"></i> Clear
</button>
</div>
</div>
<div id="imageContent" class="tab-content hidden">
<div class="mb-6">
<label class="block text-sm font-medium mb-2">Image URL</label>
<input type="text" id="imageUrl" placeholder="https://example.com/image.jpg"
class="w-full px-4 py-3 rounded-lg bg-white/10 border border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-400 text-white">
</div>
<div class="mb-6">
<label class="block text-sm font-medium mb-2">OR Upload Image</label>
<div class="flex items-center justify-center w-full">
<label for="imageUpload" class="flex flex-col items-center justify-center w-full h-64 border-2 border-white/30 border-dashed rounded-lg cursor-pointer bg-white/5 hover:bg-white/10">
<div class="flex flex-col items-center justify-center pt-5 pb-6">
<i class="fas fa-cloud-upload-alt text-4xl mb-4"></i>
<p class="mb-2 text-sm"><span class="font-semibold">Click to upload</span> or drag and drop</p>
<p class="text-xs">PNG, JPG, GIF up to 10MB</p>
</div>
<input id="imageUpload" type="file" class="hidden" accept="image/*" />
</label>
</div>
<div id="imagePreview" class="mt-4 hidden">
<img id="previewImg" class="max-h-64 mx-auto rounded-lg" />
</div>
</div>
<div class="flex space-x-4">
<button id="analyzeImageBtn" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-6 rounded-lg transition duration-300 transform hover:scale-105 pulse-border">
<i class="fas fa-search mr-2"></i> Analyze Image
</button>
<button id="clearImageBtn" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-3 px-6 rounded-lg transition duration-300">
<i class="fas fa-trash mr-2"></i> Clear
</button>
</div>
</div>
<div id="mixedContent" class="tab-content hidden">
<div class="mb-6">
<label class="block text-sm font-medium mb-2">Content Items</label>
<div id="mixedItemsContainer">
<div class="mixed-item mb-4 p-4 rounded-lg bg-white/10">
<div class="flex justify-between items-center mb-2">
<select class="item-type bg-transparent border border-white/30 rounded px-2 py-1">
<option value="text">Text</option>
<option value="image">Image</option>
</select>
<button class="remove-item text-red-400 hover:text-red-300">
<i class="fas fa-times"></i>
</button>
</div>
<div class="item-content">
<textarea class="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white" rows="3" placeholder="Enter text..."></textarea>
</div>
</div>
</div>
<button id="addItemBtn" class="mt-2 text-indigo-300 hover:text-indigo-200">
<i class="fas fa-plus-circle mr-1"></i> Add Item
</button>
</div>
<div class="flex space-x-4">
<button id="analyzeMixedBtn" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-6 rounded-lg transition duration-300 transform hover:scale-105 pulse-border">
<i class="fas fa-search mr-2"></i> Analyze All
</button>
<button id="clearMixedBtn" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-3 px-6 rounded-lg transition duration-300">
<i class="fas fa-trash mr-2"></i> Clear All
</button>
</div>
</div>
<div id="resultsSection" class="mt-8 hidden">
<h3 class="text-xl font-bold mb-4 flex items-center">
<i class="fas fa-chart-bar mr-2"></i> Analysis Results
</h3>
<div id="resultsContainer" class="space-y-4">
</div>
</div>
</div>
</div>
</div>
<div class="glass-effect p-6 rounded-xl mb-12">
<h2 class="text-2xl font-bold mb-4 flex items-center">
<i class="fas fa-tachometer-alt mr-2"></i> Performance Metrics
</h2>
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div class="bg-white/10 p-4 rounded-lg">
<div class="text-sm text-gray-300">Avg. Response Time</div>
<div class="text-2xl font-bold" id="avgResponseTime">0ms</div>
</div>
<div class="bg-white/10 p-4 rounded-lg">
<div class="text-sm text-gray-300">Concurrent Requests</div>
<div class="text-2xl font-bold" id="concurrentRequests">0</div>
</div>
<div class="bg-white/10 p-4 rounded-lg">
<div class="text-sm text-gray-300">Requests/Minute</div>
<div class="text-2xl font-bold" id="requestsPerMinute">0</div>
</div>
<div class="bg-white/10 p-4 rounded-lg">
<div class="text-sm text-gray-300">Today's Requests</div>
<div class="text-2xl font-bold" id="todayRequests">0</div>
</div>
</div>
</div>
<div class="glass-effect p-6 rounded-xl mb-12">
<h2 class="text-2xl font-bold mb-4 flex items-center">
<i class="fas fa-lightbulb mr-2"></i> Example Prompts
</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div class="example-card bg-white/10 p-4 rounded-lg cursor-pointer hover:bg-white/20 transition duration-300">
<p class="text-sm">"Hello, how are you today? I hope you're having a wonderful time!"</p>
</div>
<div class="example-card bg-white/10 p-4 rounded-lg cursor-pointer hover:bg-white/20 transition duration-300">
<p class="text-sm">"I hate you and I will find you and hurt you badly."</p>
</div>
<div class="example-card bg-white/10 p-4 rounded-lg cursor-pointer hover:bg-white/20 transition duration-300">
<p class="text-sm">"C'est une belle journée pour apprendre la programmation et l'intelligence artificielle."</p>
</div>
<div class="example-card bg-white/10 p-4 rounded-lg cursor-pointer hover:bg-white/20 transition duration-300">
<p class="text-sm">"I can't take this anymore. I want to end everything and disappear forever."</p>
</div>
<div class="example-card bg-white/10 p-4 rounded-lg cursor-pointer hover:bg-white/20 transition duration-300">
<p class="text-sm">"¡Hola! Me encanta aprender nuevos idiomas y conocer diferentes culturas."</p>
</div>
<div class="example-card bg-white/10 p-4 rounded-lg cursor-pointer hover:bg-white/20 transition duration-300">
<p class="text-sm">"You're absolutely worthless and nobody will ever love someone like you."</p>
</div>
</div>
</div>
<div class="glass-effect p-6 rounded-xl">
<h2 class="text-2xl font-bold mb-4 flex items-center">
<i class="fas fa-info-circle mr-2"></i> About This Tool
</h2>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="text-center">
<div class="inline-block p-3 rounded-full bg-indigo-500/20 mb-3">
<i class="fas fa-globe text-2xl text-indigo-300"></i>
</div>
<h3 class="text-lg font-semibold mb-2">Multilingual</h3>
<p class="text-gray-300">Supports content analysis in multiple languages with high accuracy.</p>
</div>
<div class="text-center">
<div class="inline-block p-3 rounded-full bg-indigo-500/20 mb-3">
<i class="fas fa-image text-2xl text-indigo-300"></i>
</div>
<h3 class="text-lg font-semibold mb-2">Multimodal</h3>
<p class="text-gray-300">Analyzes both text and images for comprehensive content moderation.</p>
</div>
<div class="text-center">
<div class="inline-block p-3 rounded-full bg-indigo-500/20 mb-3">
<i class="fas fa-shield-alt text-2xl text-indigo-300"></i>
</div>
<h3 class="text-lg font-semibold mb-2">Secure</h3>
<p class="text-gray-300">API key authentication ensures your requests remain secure and private.</p>
</div>
</div>
</div>
</main>
<footer class="mt-12 text-center text-gray-300">
<p>© 2023 AI Content Moderator. All rights reserved.</p>
</footer>
</div>
<div id="loadingModal" class="fixed inset-0 bg-black/70 flex items-center justify-center z-50 hidden">
<div class="glass-effect p-8 rounded-xl max-w-md w-full mx-4 text-center">
<div class="mb-4">
<div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
</div>
<h3 class="text-xl font-bold mb-2">Analyzing Content</h3>
<p class="text-gray-300">Please wait while we process your request...</p>
</div>
</div>
<script>
const textTab = document.getElementById('textTab');
const imageTab = document.getElementById('imageTab');
const mixedTab = document.getElementById('mixedTab');
const textContent = document.getElementById('textContent');
const imageContent = document.getElementById('imageContent');
const mixedContent = document.getElementById('mixedContent');
const apiKeyInput = document.getElementById('apiKey');
const toggleApiKeyBtn = document.getElementById('toggleApiKey');
const textInput = document.getElementById('textInput');
const imageUrl = document.getElementById('imageUrl');
const imageUpload = document.getElementById('imageUpload');
const imagePreview = document.getElementById('imagePreview');
const previewImg = document.getElementById('previewImg');
const analyzeTextBtn = document.getElementById('analyzeTextBtn');
const analyzeImageBtn = document.getElementById('analyzeImageBtn');
const analyzeMixedBtn = document.getElementById('analyzeMixedBtn');
const clearTextBtn = document.getElementById('clearTextBtn');
const clearImageBtn = document.getElementById('clearImageBtn');
const clearMixedBtn = document.getElementById('clearMixedBtn');
const resultsSection = document.getElementById('resultsSection');
const resultsContainer = document.getElementById('resultsContainer');
const loadingModal = document.getElementById('loadingModal');
const mixedItemsContainer = document.getElementById('mixedItemsContainer');
const addItemBtn = document.getElementById('addItemBtn');
const exampleCards = document.querySelectorAll('.example-card');
textTab.addEventListener('click', () => {
textTab.classList.add('border-indigo-400', 'text-indigo-300');
textTab.classList.remove('border-transparent', 'text-gray-300');
imageTab.classList.add('border-transparent', 'text-gray-300');
imageTab.classList.remove('border-indigo-400', 'text-indigo-300');
mixedTab.classList.add('border-transparent', 'text-gray-300');
mixedTab.classList.remove('border-indigo-400', 'text-indigo-300');
textContent.classList.remove('hidden');
imageContent.classList.add('hidden');
mixedContent.classList.add('hidden');
});
imageTab.addEventListener('click', () => {
imageTab.classList.add('border-indigo-400', 'text-indigo-300');
imageTab.classList.remove('border-transparent', 'text-gray-300');
textTab.classList.add('border-transparent', 'text-gray-300');
textTab.classList.remove('border-indigo-400', 'text-indigo-300');
mixedTab.classList.add('border-transparent', 'text-gray-300');
mixedTab.classList.remove('border-indigo-400', 'text-indigo-300');
imageContent.classList.remove('hidden');
textContent.classList.add('hidden');
mixedContent.classList.add('hidden');
});
mixedTab.addEventListener('click', () => {
mixedTab.classList.add('border-indigo-400', 'text-indigo-300');
mixedTab.classList.remove('border-transparent', 'text-gray-300');
textTab.classList.add('border-transparent', 'text-gray-300');
textTab.classList.remove('border-indigo-400', 'text-indigo-300');
imageTab.classList.add('border-transparent', 'text-gray-300');
imageTab.classList.remove('border-indigo-400', 'text-indigo-300');
mixedContent.classList.remove('hidden');
textContent.classList.add('hidden');
imageContent.classList.add('hidden');
});
toggleApiKeyBtn.addEventListener('click', () => {
const type = apiKeyInput.getAttribute('type') === 'password' ? 'text' : 'password';
apiKeyInput.setAttribute('type', type);
toggleApiKeyBtn.innerHTML = type === 'password' ? '<i class="fas fa-eye"></i>' : '<i class="fas fa-eye-slash"></i>';
});
imageUpload.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
previewImg.src = event.target.result;
imagePreview.classList.remove('hidden');
};
reader.readAsDataURL(file);
}
});
exampleCards.forEach(card => {
card.addEventListener('click', () => {
textInput.value = card.querySelector('p').textContent;
});
});
clearTextBtn.addEventListener('click', () => {
textInput.value = '';
resultsSection.classList.add('hidden');
});
clearImageBtn.addEventListener('click', () => {
imageUrl.value = '';
imageUpload.value = '';
imagePreview.classList.add('hidden');
resultsSection.classList.add('hidden');
});
clearMixedBtn.addEventListener('click', () => {
mixedItemsContainer.innerHTML = '';
addMixedItem();
resultsSection.classList.add('hidden');
});
addItemBtn.addEventListener('click', addMixedItem);
function addMixedItem() {
if (mixedItemsContainer.children.length >= 10) {
showNotification('Maximum 10 items allowed', 'error');
return;
}
const itemDiv = document.createElement('div');
itemDiv.className = 'mixed-item mb-4 p-4 rounded-lg bg-white/10';
itemDiv.innerHTML = `
<div class="flex justify-between items-center mb-2">
<select class="item-type bg-transparent border border-white/30 rounded px-2 py-1">
<option value="text">Text</option>
<option value="image">Image</option>
</select>
<button class="remove-item text-red-400 hover:text-red-300">
<i class="fas fa-times"></i>
</button>
</div>
<div class="item-content">
<textarea class="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white" rows="3" placeholder="Enter text..."></textarea>
</div>
`;
mixedItemsContainer.appendChild(itemDiv);
const typeSelect = itemDiv.querySelector('.item-type');
const contentDiv = itemDiv.querySelector('.item-content');
const removeBtn = itemDiv.querySelector('.remove-item');
typeSelect.addEventListener('change', () => {
if (typeSelect.value === 'text') {
contentDiv.innerHTML = '<textarea class="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white" rows="3" placeholder="Enter text..."></textarea>';
} else {
contentDiv.innerHTML = `
<input type="text" class="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white mb-2" placeholder="Image URL or leave empty to upload">
<div class="flex items-center justify-center w-full">
<label class="flex flex-col items-center justify-center w-full h-32 border-2 border-white/30 border-dashed rounded-lg cursor-pointer bg-white/5 hover:bg-white/10">
<div class="flex flex-col items-center justify-center pt-2 pb-3">
<i class="fas fa-cloud-upload-alt text-2xl mb-2"></i>
<p class="text-xs">Upload image</p>
</div>
<input type="file" class="hidden" accept="image/*" />
</label>
</div>
<div class="image-preview mt-2 hidden">
<img class="max-h-32 mx-auto rounded" />
</div>
`;
const fileInput = contentDiv.querySelector('input[type="file"]');
const preview = contentDiv.querySelector('.image-preview');
const previewImg = contentDiv.querySelector('.image-preview img');
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
previewImg.src = event.target.result;
preview.classList.remove('hidden');
};
reader.readAsDataURL(file);
}
});
}
});
removeBtn.addEventListener('click', () => {
itemDiv.remove();
updateRemoveButtons();
});
updateRemoveButtons();
}
function updateRemoveButtons() {
const items = mixedItemsContainer.querySelectorAll('.mixed-item');
items.forEach(item => {
const removeBtn = item.querySelector('.remove-item');
removeBtn.style.display = items.length > 1 ? 'block' : 'none';
});
}
mixedItemsContainer.addEventListener('click', (e) => {
if (e.target.closest('.remove-item')) {
e.target.closest('.mixed-item').remove();
updateRemoveButtons();
}
});
analyzeTextBtn.addEventListener('click', async () => {
const text = textInput.value.trim();
if (!text) {
showNotification('Please enter text to analyze', 'error');
return;
}
const apiKey = apiKeyInput.value.trim();
if (!apiKey) {
showNotification('Please enter your API key', 'error');
return;
}
showLoading(true);
try {
const response = await fetch('/v1/moderations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
input: text,
model: document.getElementById('modelSelect').value
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'An error occurred');
}
const data = await response.json();
displayResults(data.results);
updateMetrics();
} catch (error) {
showNotification(`Error: ${error.message}`, 'error');
} finally {
showLoading(false);
}
});
analyzeImageBtn.addEventListener('click', async () => {
const url = imageUrl.value.trim();
const fileInput = document.querySelector('#imageUpload');
const file = fileInput.files[0];
if (!url && !file) {
showNotification('Please provide an image URL or upload an image', 'error');
return;
}
const apiKey = apiKeyInput.value.trim();
if (!apiKey) {
showNotification('Please enter your API key', 'error');
return;
}
let imageInput;
if (url) {
imageInput = {
type: "image",
url: url
};
} else {
const reader = new FileReader();
const base64Promise = new Promise((resolve) => {
reader.onload = (event) => resolve(event.target.result);
});
reader.readAsDataURL(file);
const base64 = await base64Promise;
imageInput = {
type: "image",
base64: base64
};
}
showLoading(true);
try {
const response = await fetch('/v1/moderations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
input: [imageInput],
model: document.getElementById('modelSelect').value
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'An error occurred');
}
const data = await response.json();
displayResults(data.results);
updateMetrics();
} catch (error) {
showNotification(`Error: ${error.message}`, 'error');
} finally {
showLoading(false);
}
});
analyzeMixedBtn.addEventListener('click', async () => {
const items = Array.from(mixedItemsContainer.querySelectorAll('.mixed-item'));
if (items.length === 0) {
showNotification('Please add at least one item to analyze', 'error');
return;
}
const apiKey = apiKeyInput.value.trim();
if (!apiKey) {
showNotification('Please enter your API key', 'error');
return;
}
const inputItems = [];
for (const item of items) {
const type = item.querySelector('.item-type').value;
const contentDiv = item.querySelector('.item-content');
if (type === 'text') {
const textarea = contentDiv.querySelector('textarea');
const text = textarea.value.trim();
if (text) {
inputItems.push({
type: 'text',
text: text
});
}
} else {
const urlInput = contentDiv.querySelector('input[type="text"]');
const fileInput = contentDiv.querySelector('input[type="file"]');
const preview = contentDiv.querySelector('.image-preview');
const previewImg = contentDiv.querySelector('.image-preview img');
const url = urlInput.value.trim();
const file = fileInput.files[0];
if (url) {
inputItems.push({
type: 'image',
url: url
});
} else if (file || !preview.classList.contains('hidden')) {
const imgSrc = previewImg.src;
inputItems.push({
type: 'image',
base64: imgSrc
});
}
}
}
if (inputItems.length === 0) {
showNotification('Please add content to at least one item', 'error');
return;
}
showLoading(true);
try {
const response = await fetch('/v1/moderations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
input: inputItems,
model: document.getElementById('modelSelect').value
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'An error occurred');
}
const data = await response.json();
displayResults(data.results);
updateMetrics();
} catch (error) {
showNotification(`Error: ${error.message}`, 'error');
} finally {
showLoading(false);
}
});
function displayResults(results) {
resultsContainer.innerHTML = '';
results.forEach((result, index) => {
const isFlagged = result.flagged;
const cardClass = isFlagged ? 'unsafe-gradient' : 'safe-gradient';
const icon = isFlagged ? 'fas fa-exclamation-triangle' : 'fas fa-check-circle';
const statusText = isFlagged ? 'UNSAFE' : 'SAFE';
const statusDesc = isFlagged ?
'Content may contain inappropriate or harmful material.' :
'Content appears to be safe and appropriate.';
const categories = Object.entries(result.categories)
.filter(([_, value]) => value)
.map(([key, _]) => key.replace('/', ' '))
.join(', ');
let contentPreview = '';
if (result.text) {
contentPreview = `<div class="bg-black/20 p-4 rounded-lg mb-4">
<p class="text-sm font-mono break-words">${result.text}</p>
</div>`;
} else if (result.image_url) {
contentPreview = `<div class="bg-black/20 p-4 rounded-lg mb-4 text-center">
<img src="${result.image_url}" class="max-h-48 mx-auto rounded" />
</div>`;
} else if (result.image_base64) {
contentPreview = `<div class="bg-black/20 p-4 rounded-lg mb-4 text-center">
<img src="${result.image_base64}" class="max-h-48 mx-auto rounded" />
</div>`;
}
const resultCard = document.createElement('div');
resultCard.className = `p-6 rounded-xl text-white ${cardClass} shadow-lg`;
resultCard.innerHTML = `
<div class="flex items-start">
<div class="mr-4 mt-1">
<i class="${icon} text-3xl"></i>
</div>
<div class="flex-1">
<div class="flex justify-between items-start mb-2">
<h3 class="text-xl font-bold">${statusText}</h3>
<span class="text-sm bg-black/20 px-2 py-1 rounded">Item ${index + 1}</span>
</div>
<p class="mb-4">${statusDesc}</p>
${contentPreview}
${isFlagged ? `
<div class="mb-3">
<h4 class="font-semibold mb-1">Flagged Categories:</h4>
<p class="text-sm">${categories}</p>
</div>
` : ''}
<div class="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
${Object.entries(result.category_scores).map(([category, score]) => `
<div class="bg-black/20 p-2 rounded">
<div class="font-medium">${category.replace('/', ' ')}</div>
<div class="w-full bg-gray-700 rounded-full h-1.5 mt-1">
<div class="bg-white h-1.5 rounded-full" style="width: ${score * 100}%"></div>
</div>
<div class="text-right mt-1">${(score * 100).toFixed(0)}%</div>
</div>
`).join('')}
</div>
</div>
</div>
`;
resultsContainer.appendChild(resultCard);
});
resultsSection.classList.remove('hidden');
resultsSection.scrollIntoView({ behavior: 'smooth' });
}
async function updateMetrics() {
const apiKey = apiKeyInput.value.trim() || 'temp-key-for-metrics';
try {
const response = await fetch('/v1/metrics', {
headers: { 'Authorization': 'Bearer ' + apiKey }
});
if (response.ok) {
const data = await response.json();
document.getElementById('avgResponseTime').textContent = data.avg_request_time_ms.toFixed(0) + 'ms';
document.getElementById('concurrentRequests').textContent = data.concurrent_requests;
document.getElementById('requestsPerMinute').textContent = data.requests_per_minute;
document.getElementById('todayRequests').textContent = data.today_requests;
}
} catch (error) {
console.error('Error updating metrics:', error);
}
}
function showLoading(show) {
if (show) {
loadingModal.classList.remove('hidden');
} else {
loadingModal.classList.add('hidden');
}
}
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
type === 'error' ? 'bg-red-500' : 'bg-indigo-500'
} text-white`;
notification.innerHTML = `
<div class="flex items-center">
<i class="fas ${type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'} mr-2"></i>
<span>${message}</span>
</div>
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transition = 'opacity 0.5s';
setTimeout(() => {
document.body.removeChild(notification);
}, 500);
}, 3000);
}
document.addEventListener('DOMContentLoaded', () => {
addMixedItem();
updateMetrics();
setInterval(updateMetrics, 30000);
});
</script>
</body>
</html>""")
print("Initializing models...")
with torch.inference_mode():
_ = model.generate(
**tokenizer(["Hello"], return_tensors="pt").to(model.device),
max_new_tokens=1, do_sample=False, use_cache=True
)
print("🚀 Starting AI Content Moderator API...")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |