File size: 57,139 Bytes
509d66d
54ba978
478bcd0
cc6f54d
692a239
509d66d
 
 
478bcd0
 
 
509d66d
478bcd0
509d66d
478bcd0
509d66d
478bcd0
509d66d
478bcd0
 
 
509d66d
 
 
 
 
478bcd0
509d66d
478bcd0
 
 
509d66d
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
509d66d
478bcd0
509d66d
478bcd0
 
509d66d
 
 
 
5a39cfb
478bcd0
509d66d
 
688f230
509d66d
478bcd0
509d66d
 
 
b3e6062
509d66d
688f230
478bcd0
 
509d66d
478bcd0
 
509d66d
478bcd0
 
509d66d
478bcd0
 
f0b5304
509d66d
 
 
 
 
 
 
478bcd0
 
 
509d66d
 
 
 
 
478bcd0
 
 
 
 
 
509d66d
478bcd0
509d66d
478bcd0
 
 
 
 
 
509d66d
478bcd0
688f230
478bcd0
 
 
 
 
 
 
 
688f230
478bcd0
 
688f230
478bcd0
509d66d
688f230
509d66d
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
478bcd0
 
509d66d
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
509d66d
 
 
 
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
 
 
509d66d
 
478bcd0
 
509d66d
 
 
478bcd0
 
509d66d
 
478bcd0
509d66d
 
 
478bcd0
 
 
 
 
 
509d66d
 
 
 
 
478bcd0
688f230
478bcd0
688f230
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
 
 
509d66d
 
 
 
688f230
 
 
 
509d66d
688f230
478bcd0
688f230
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
688f230
478bcd0
 
509d66d
 
 
 
 
 
 
478bcd0
 
688f230
 
478bcd0
 
 
 
 
509d66d
688f230
478bcd0
688f230
509d66d
 
 
 
 
478bcd0
 
 
688f230
478bcd0
 
 
 
 
509d66d
 
 
 
 
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
509d66d
478bcd0
 
509d66d
 
 
478bcd0
 
 
 
509d66d
 
 
 
 
478bcd0
 
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
 
 
 
 
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
509d66d
478bcd0
509d66d
 
 
 
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
688f230
 
478bcd0
 
509d66d
478bcd0
509d66d
 
688f230
478bcd0
509d66d
688f230
478bcd0
509d66d
 
478bcd0
509d66d
478bcd0
509d66d
478bcd0
509d66d
 
688f230
 
478bcd0
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
509d66d
688f230
509d66d
 
 
 
 
 
 
 
 
478bcd0
509d66d
 
 
 
 
478bcd0
688f230
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
 
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478bcd0
 
509d66d
478bcd0
509d66d
 
 
 
 
478bcd0
 
509d66d
 
478bcd0
509d66d
 
 
688f230
478bcd0
688f230
478bcd0
509d66d
688f230
509d66d
 
 
688f230
509d66d
 
 
478bcd0
509d66d
688f230
509d66d
688f230
509d66d
478bcd0
688f230
 
 
509d66d
 
478bcd0
509d66d
 
688f230
 
509d66d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
688f230
 
478bcd0
509d66d
 
478bcd0
509d66d
478bcd0
688f230
 
 
509d66d
478bcd0
 
509d66d
 
 
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
from flask import Flask, request, jsonify, render_template
import os
import uuid
import time
import threading
import tiktoken
import requests
import base64
from datetime import datetime, timedelta
from collections import defaultdict, deque
from detoxify import Detoxify
import logging

logging.basicConfig(level=logging.INFO)

app = Flask(__name__, static_folder='static', template_folder='templates')

print("Loading Detoxify model... This may take a moment.")
detoxify_model = Detoxify('multilingual')
print("Detoxify model loaded successfully.")

API_KEY = os.getenv('API_KEY', 'your-api-key-here')

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")

NSFW_MODEL_URL = "https://teachablemachine.withgoogle.com/models/gJOADmf_u/"

def count_tokens(text):
    return len(encoding.encode(text))

def classify_image_nsfw(image_data):
    try:
        response = requests.post(
            NSFW_MODEL_URL,
            json={"instances": [{"image_bytes": {"b64": image_data}}]},
            timeout=10
        )
        if response.status_code == 200:
            predictions = response.json().get('predictions', [{}])[0]
            nsfw_score = predictions.get('nsfw', 0.0)
            return nsfw_score > 0.5
        return False
    except:
        return False

def transform_predictions(prediction_dict):
    category_keys = [
        "toxicity", "severe_toxicity", "obscene", "threat", 
        "insult", "identity_attack", "sexual_explicit"
    ]
    
    scores = {}
    for key in category_keys:
        scores[key] = float(prediction_dict.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, bool_categories, scores

def track_request_metrics(start_time, tokens_count):
    end_time = time.time()
    duration = end_time - start_time
    
    app.logger.info(f"Server-side processing for moderation request took {duration * 1000:.2f} ms.")
    
    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
    }

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/v1/moderations', methods=['POST'])
def moderations():
    global concurrent_requests
    
    with concurrent_requests_lock:
        concurrent_requests += 1
    
    start_time = time.time()
    total_tokens = 0
    
    response = None
    try:
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith("Bearer "):
            response = jsonify({"error": "Unauthorized"}), 401
            return response
        
        provided_api_key = auth_header.split(" ")[1]
        if provided_api_key != API_KEY:
            response = jsonify({"error": "Unauthorized"}), 401
            return response
        
        data = request.get_json()
        raw_input = data.get('input')
        
        if raw_input is None:
            response = jsonify({"error": "Invalid input, 'input' field is required"}), 400
            return response
        
        if isinstance(raw_input, str):
            texts = [raw_input]
        elif isinstance(raw_input, list):
            texts = raw_input
        else:
            response = jsonify({"error": "Invalid input format, expected string or list of strings"}), 400
            return response
        
        if not texts:
            response = jsonify({"error": "Input list cannot be empty"}), 400
            return response

        if len(texts) > 10:
            response = jsonify({"error": "Too many input items. Maximum 10 allowed."}), 400
            return response
        
        results = []
        for text in texts:
            if not isinstance(text, str):
                if isinstance(text, dict) and 'type' in text and text['type'] == 'image_url':
                    image_data = text.get('image_url', {}).get('url', '')
                    if image_data.startswith('data:image'):
                        image_b64 = image_data.split(',')[1]
                        is_nsfw = classify_image_nsfw(image_b64)
                        
                        results.append({
                            "flagged": is_nsfw,
                            "categories": {
                                "sexual": is_nsfw,
                                "sexual_explicit": is_nsfw
                            },
                            "category_scores": {
                                "sexual": 0.9 if is_nsfw else 0.1,
                                "sexual_explicit": 0.9 if is_nsfw else 0.1
                            }
                        })
                        continue
                response = jsonify({"error": "Each input item must be a string or image object"}), 400
                return response
            
            if len(text.encode('utf-8')) > 300000:
                response = jsonify({"error": "Each input item must have a maximum of 300k bytes."}), 400
                return response
            
            total_tokens += count_tokens(text)
            
            predictions = detoxify_model.predict([text])
            single_prediction = {key: value[0] for key, value in predictions.items()}
            flagged, bool_categories, scores = transform_predictions(single_prediction)
            
            results.append({
                "flagged": flagged,
                "categories": bool_categories,
                "category_scores": scores,
            })
        
        response_data = {
            "id": "modr-" + uuid.uuid4().hex[:24],
            "model": "text-moderation-detoxify-multilingual",
            "results": results
        }
        
        response = jsonify(response_data)
        return response
    
    except Exception as e:
        app.logger.error(f"An error occurred: {e}", exc_info=True)
        response = jsonify({"error": "An internal server error occurred."}), 500
        return response
    finally:
        if response and (response[1] < 400 if isinstance(response, tuple) else response.status_code < 400):
            track_request_metrics(start_time, total_tokens)
        
        with concurrent_requests_lock:
            concurrent_requests -= 1

@app.route('/v1/metrics', methods=['GET'])
def metrics():
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith("Bearer "):
        return jsonify({"error": "Unauthorized"}), 401
    
    provided_api_key = auth_header.split(" ")[1]
    if provided_api_key != API_KEY:
        return jsonify({"error": "Unauthorized"}), 401
    
    return jsonify(get_performance_metrics())

# Create the HTML template with Tailwind CSS
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">Smart Moderator</h1>
            <p class="text-xl text-gray-200 max-w-2xl mx-auto">
                Advanced, multilingual and multimodal content moderation API
            </p>
        </header>

        <main class="max-w-6xl mx-auto">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-12">
                <!-- API Key Section -->
                <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="text-moderation-detoxify-multilingual" selected>Detoxify Multilingual</option>
                            </select>
                        </div>
                        <div class="mt-6">
                            <h3 class="text-lg font-semibold mb-2">API Usage</h3>
                            <div class="bg-black/20 p-4 rounded-lg text-sm font-mono">
                                <div class="mb-2">POST /v1/moderations</div>
                                <div class="mb-2">Site: https://nixaut-codelabs-smart-moderator.hf.space</div>
                                <div class="text-xs text-gray-300">curl -X POST -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{"input":"text to moderate"}' /v1/moderations</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Main Content Section -->
                <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>
                        
                        <!-- Tabs -->
                        <div class="flex border-b border-white/20 mb-6">
                            <button id="singleTab" class="px-4 py-2 font-medium border-b-2 border-indigo-400 text-indigo-300 tab-active">
                                Single Text
                            </button>
                            <button id="batchTab" class="px-4 py-2 font-medium border-b-2 border-transparent text-gray-300 hover:text-white">
                                Batch Processing
                            </button>
                        </div>
                        
                        <!-- Single Text Tab -->
                        <div id="singleContent" 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="analyzeBtn" 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 Content
                                </button>
                                <button id="clearBtn" 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>
                        
                        <!-- Batch Processing Tab -->
                        <div id="batchContent" class="tab-content hidden">
                            <div class="mb-6">
                                <label class="block text-sm font-medium mb-2">Texts to Analyze (one per line)</label>
                                <textarea id="batchTextInput" rows="8" placeholder="Enter multiple texts, one per line..."
                                    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="batchAnalyzeBtn" 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-layer-group mr-2"></i> Analyze Batch
                                </button>
                                <button id="batchClearBtn" 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>
                        
                        <!-- Results Section -->
                        <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">
                                <!-- Results will be dynamically inserted here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Examples Section -->
            <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>

            <!-- Information Section -->
            <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-bolt text-2xl text-indigo-300"></i>
                        </div>
                        <h3 class="text-lg font-semibold mb-2">Fast Processing</h3>
                        <p class="text-gray-300">Optimized model for quick content analysis with real-time results.</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>© 2025 Smart Moderator. All rights reserved.</p>
        </footer>
    </div>

    <!-- Loading Modal -->
    <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>
        // DOM Elements
        const singleTab = document.getElementById('singleTab');
        const batchTab = document.getElementById('batchTab');
        const singleContent = document.getElementById('singleContent');
        const batchContent = document.getElementById('batchContent');
        const apiKeyInput = document.getElementById('apiKey');
        const toggleApiKeyBtn = document.getElementById('toggleApiKey');
        const textInput = document.getElementById('textInput');
        const batchTextInput = document.getElementById('batchTextInput');
        const analyzeBtn = document.getElementById('analyzeBtn');
        const batchAnalyzeBtn = document.getElementById('batchAnalyzeBtn');
        const clearBtn = document.getElementById('clearBtn');
        const batchClearBtn = document.getElementById('batchClearBtn');
        const resultsSection = document.getElementById('resultsSection');
        const resultsContainer = document.getElementById('resultsContainer');
        const loadingModal = document.getElementById('loadingModal');
        const exampleCards = document.querySelectorAll('.example-card');

        // Tab switching
        singleTab.addEventListener('click', () => {
            singleTab.classList.add('border-indigo-400', 'text-indigo-300');
            singleTab.classList.remove('border-transparent', 'text-gray-300');
            batchTab.classList.add('border-transparent', 'text-gray-300');
            batchTab.classList.remove('border-indigo-400', 'text-indigo-300');
            singleContent.classList.remove('hidden');
            batchContent.classList.add('hidden');
        });

        batchTab.addEventListener('click', () => {
            batchTab.classList.add('border-indigo-400', 'text-indigo-300');
            batchTab.classList.remove('border-transparent', 'text-gray-300');
            singleTab.classList.add('border-transparent', 'text-gray-300');
            singleTab.classList.remove('border-indigo-400', 'text-indigo-300');
            batchContent.classList.remove('hidden');
            singleContent.classList.add('hidden');
        });

        // Toggle API key visibility
        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>';
        });

        // Slider value updates
        maxTokensSlider.addEventListener('input', () => {
            maxTokensValue.textContent = maxTokensSlider.value;
        });

        temperatureSlider.addEventListener('input', () => {
            temperatureValue.textContent = temperatureSlider.value;
        });

        topPSlider.addEventListener('input', () => {
            topPValue.textContent = topPSlider.value;
        });

        // Example cards
        exampleCards.forEach(card => {
            card.addEventListener('click', () => {
                textInput.value = card.querySelector('p').textContent;
            });
        });

        // Clear buttons
        clearBtn.addEventListener('click', () => {
            textInput.value = '';
            resultsSection.classList.add('hidden');
        });

        batchClearBtn.addEventListener('click', () => {
            batchTextInput.value = '';
            resultsSection.classList.add('hidden');
        });

        // Analyze button
        analyzeBtn.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[0]]);
            } catch (error) {
                showNotification(`Error: ${error.message}`, 'error');
            } finally {
                showLoading(false);
            }
        });

        // Batch analyze button
        batchAnalyzeBtn.addEventListener('click', async () => {
            const texts = batchTextInput.value.trim().split('\\n').filter(text => text.trim());
            if (texts.length === 0) {
                showNotification('Please enter at least one 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: texts,
                        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);
            } catch (error) {
                showNotification(`Error: ${error.message}`, 'error');
            } finally {
                showLoading(false);
            }
        });

        // Display results
        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(', ');

                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">Result ${index + 1}</span>
                            </div>
                            <p class="mb-4">${statusDesc}</p>
                            <div class="bg-black/20 p-4 rounded-lg mb-4">
                                <p class="text-sm font-mono break-words">${result.text}</p>
                            </div>
                            ${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' });
        }

        // Show/hide loading modal
        function showLoading(show) {
            if (show) {
                loadingModal.classList.remove('hidden');
            } else {
                loadingModal.classList.add('hidden');
            }
        }

        // Show notification
        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);
        }
    </script>
</body>
</html>
""")

def create_directories_and_files():
    os.makedirs('templates', exist_ok=True)
    os.makedirs('static', exist_ok=True)
    
    index_path = os.path.join('templates', 'index.html')
    if not os.path.exists(index_path):
        with open(index_path, 'w', encoding='utf-8') 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>Smart Moderator</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff', 100: '#dbeafe', 200: '#bfdbfe', 300: '#93c5fd', 400: '#60a5fa',
                            500: '#3b82f6', 600: '#2563eb', 700: '#1d4ed8', 800: '#1e40af', 900: '#1e3a8a',
                        }
                    }
                }
            }
        }
    </script>
    <style>
        .gradient-bg { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .dark .gradient-bg { background: linear-gradient(135deg, #1e3a8a 0%, #4c1d95 100%); }
        .glass-effect {
            background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .dark .glass-effect { background: rgba(30, 41, 59, 0.5); border: 1px solid rgba(100, 116, 139, 0.3); }
        .category-card { transition: all 0.3s ease; }
        .category-card:hover { transform: translateY(-5px); }
        .loading-spinner { border-top-color: #3b82f6; animation: spinner 1.5s linear infinite; }
        @keyframes spinner { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body class="bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 min-h-screen font-sans">
    <header class="gradient-bg text-white shadow-lg">
        <div class="container mx-auto px-4 py-6 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <div class="w-10 h-10 rounded-full bg-white flex items-center justify-center">
                    <i class="fas fa-shield-alt text-primary-600 text-xl"></i>
                </div>
                <h1 class="text-2xl font-bold">Smart Moderator</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button id="refreshMetrics" class="glass-effect px-4 py-2 rounded-lg hover:bg-white/20 transition">
                    <i class="fas fa-sync-alt mr-2"></i>Refresh Metrics
                </button>
                <button id="darkModeToggle" class="glass-effect p-2 rounded-lg hover:bg-white/20 transition">
                    <i class="fas fa-moon dark:hidden"></i>
                    <i class="fas fa-sun hidden dark:inline"></i>
                </button>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <section class="mb-12">
            <h2 class="text-2xl font-bold mb-6 flex items-center">
                <i class="fas fa-chart-line mr-3 text-primary-600"></i>
                Performance Metrics
            </h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 dark:text-gray-400 text-sm">Avg. Response (last 100)</p>
                            <p class="text-2xl font-bold" id="avgResponseTime">0ms</p>
                        </div>
                        <div class="w-12 h-12 rounded-full bg-primary-100 dark:bg-primary-900/30 flex items-center justify-center">
                            <i class="fas fa-clock text-primary-600 dark:text-primary-400"></i>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 dark:text-gray-400 text-sm">Requests / Minute</p>
                            <p class="text-2xl font-bold" id="requestsPerMinute">0</p>
                        </div>
                        <div class="w-12 h-12 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
                            <i class="fas fa-tachometer-alt text-green-600 dark:text-green-400"></i>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 dark:text-gray-400 text-sm">Peak Response (last 100)</p>
                            <p class="text-2xl font-bold" id="peakResponseTime">0ms</p>
                        </div>
                        <div class="w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                            <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400"></i>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 dark:text-gray-400 text-sm">Today's Requests</p>
                            <p class="text-2xl font-bold" id="todayRequests">0</p>
                        </div>
                        <div class="w-12 h-12 rounded-full bg-yellow-100 dark:bg-yellow-900/30 flex items-center justify-center">
                            <i class="fas fa-list-ol text-yellow-600 dark:text-yellow-400"></i>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                <h3 class="text-lg font-semibold mb-4">Last 7 Days Activity</h3>
                <div class="h-64">
                    <canvas id="activityChart"></canvas>
                </div>
            </div>
        </section>

        <section class="mb-12">
            <h2 class="text-2xl font-bold mb-6 flex items-center">
                <i class="fas fa-code mr-3 text-primary-600"></i>
                API Tester
            </h2>
            
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                <form id="apiTestForm">
                    <div class="mb-6">
                        <label class="block text-sm font-medium mb-2" for="apiKey">API Key</label>
                        <input type="password" id="apiKey" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-primary-500" placeholder="Enter your API key">
                    </div>
                    
                    <div class="mb-6">
                        <label class="block text-sm font-medium mb-2">Text Inputs</label>
                        <div id="textInputsContainer">
                            <div class="text-input-group mb-4">
                                <textarea class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-primary-500" rows="3" placeholder="Enter text to moderate..."></textarea>
                                <button type="button" class="remove-input mt-2 text-red-500 hover:text-red-700 hidden">
                                    <i class="fas fa-trash-alt mr-1"></i> Remove
                                </button>
                            </div>
                        </div>
                        <button type="button" id="addTextInput" class="mt-2 text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300">
                            <i class="fas fa-plus-circle mr-1"></i> Add another text input
                        </button>
                    </div>
                    
                    <div class="flex justify-between items-center">
                        <div>
                            <button type="submit" id="analyzeBtn" class="bg-primary-600 hover:bg-primary-700 text-white font-medium py-2 px-6 rounded-lg transition">
                                <i class="fas fa-search mr-2"></i> Analyze Text
                            </button>
                            <button type="button" id="clearBtn" class="ml-2 bg-gray-300 hover:bg-gray-400 dark:bg-gray-600 dark:hover:bg-gray-700 text-gray-800 dark:text-gray-200 font-medium py-2 px-6 rounded-lg transition">
                                <i class="fas fa-eraser mr-2"></i> Clear
                            </button>
                        </div>
                        <div class="text-sm text-gray-500 dark:text-gray-400">
                            <i class="fas fa-info-circle mr-1"></i> Maximum 10 text inputs allowed
                        </div>
                    </div>
                </form>
            </div>
        </section>

        <section id="resultsSection" class="hidden">
            <h2 class="text-2xl font-bold mb-6 flex items-center">
                <i class="fas fa-clipboard-check mr-3 text-primary-600"></i>
                Analysis Results
            </h2>
            
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">Summary</h3>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                        <i class="fas fa-stopwatch mr-1"></i> Round-trip time: <span id="responseTime">0ms</span>
                    </div>
                </div>
                
                <div id="resultsContainer" class="space-y-6">
                </div>
            </div>
        </section>

        <section>
            <h2 class="text-2xl font-bold mb-6 flex items-center">
                <i class="fas fa-book mr-3 text-primary-600"></i>
                API Documentation
            </h2>
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
                <h3 class="text-lg font-semibold mb-4">Endpoint</h3>
                <div class="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg mb-6 font-mono text-sm">POST /v1/moderations</div>
                <h3 class="text-lg font-semibold mb-4">Site URL</h3>
                <div class="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg mb-6 font-mono text-sm">https://nixaut-codelabs-smart-moderator.hf.space</div>
                <h3 class="text-lg font-semibold mb-4">Request Body</h3>
                <div class="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg mb-6 overflow-x-auto">
                    <pre class="text-sm"><code>{
  "input": "Text to moderate" 
}</code></pre>
                </div>
                <h3 class="text-lg font-semibold mb-4">Response</h3>
                <div class="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg overflow-x-auto">
                    <pre class="text-sm"><code>{
  "id": "modr-1234567890abcdef",
  "model": "text-moderation-detoxify-multilingual",
  "results": [
    {
      "flagged": true,
      "categories": {
        "toxicity": true,
        "severe_toxicity": false,
        /* ... other categories */
      },
      "category_scores": {
        "toxicity": 0.95,
        "severe_toxicity": 0.1,
        /* ... other scores */
      }
    }
  ]
}</code></pre>
                </div>
            </div>
        </section>
    </main>

    <footer class="bg-gray-100 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 mt-12">
        <div class="container mx-auto px-4 py-6 text-center text-gray-600 dark:text-gray-400">
            2025 Smart Moderator. All rights reserved.
        </div>
    </footer>

    <script>
        const darkModeToggle = document.getElementById('darkModeToggle');
        const html = document.documentElement;
        
        if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            html.classList.add('dark');
        }
        
        darkModeToggle.addEventListener('click', () => {
            html.classList.toggle('dark');
            localStorage.setItem('theme', html.classList.contains('dark') ? 'dark' : 'light');
        });

        let activityChart;
        
        function initActivityChart() {
            if (activityChart) { activityChart.destroy(); }
            const ctx = document.getElementById('activityChart').getContext('2d');
            const isDarkMode = document.documentElement.classList.contains('dark');
            const gridColor = isDarkMode ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)';
            const textColor = isDarkMode ? '#e5e7eb' : '#374151';

            activityChart = new Chart(ctx, {
                type: 'bar',
                data: { labels: [], datasets: [
                    { label: 'Requests', data: [], backgroundColor: 'rgba(59, 130, 246, 0.6)', borderColor: 'rgba(59, 130, 246, 1)', borderWidth: 1 },
                    { label: 'Tokens', data: [], backgroundColor: 'rgba(16, 185, 129, 0.6)', borderColor: 'rgba(16, 185, 129, 1)', borderWidth: 1, yAxisID: 'y1' }
                ]},
                options: {
                    responsive: true, maintainAspectRatio: false,
                    scales: {
                        y: { beginAtZero: true, position: 'left', title: { display: true, text: 'Requests', color: textColor }, ticks: { color: textColor }, grid: { color: gridColor } },
                        y1: { beginAtZero: true, position: 'right', title: { display: true, text: 'Tokens', color: textColor }, ticks: { color: textColor }, grid: { drawOnChartArea: false } }
                    },
                    plugins: { legend: { labels: { color: textColor } } }
                }
            });
        }

        async function fetchMetrics() {
            const apiKey = document.getElementById('apiKey').value || 'temp-key-for-metrics';
            try {
                const response = await fetch('/v1/metrics', {
                    headers: { 'Authorization': 'Bearer ' + apiKey }
                });
                if (!response.ok) {
                    const error = await response.json();
                    console.error('Failed to fetch metrics:', error.error);
                    if(response.status === 401) {
                    }
                    return;
                }
                const data = await response.json();
                updateMetricsDisplay(data);
            } catch (error) {
                console.error('Error fetching metrics:', error);
            }
        }

        function updateMetricsDisplay(data) {
            document.getElementById('avgResponseTime').textContent = data.avg_request_time_ms.toFixed(0) + 'ms';
            document.getElementById('peakResponseTime').textContent = data.peak_request_time_ms.toFixed(0) + 'ms';
            document.getElementById('requestsPerMinute').textContent = data.requests_per_minute;
            document.getElementById('todayRequests').textContent = data.today_requests.toLocaleString();

            if (activityChart) {
                const labels = data.last_7_days.map(d => new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })).reverse();
                const requests = data.last_7_days.map(d => d.requests).reverse();
                const tokens = data.last_7_days.map(d => d.tokens).reverse();
                
                activityChart.data.labels = labels;
                activityChart.data.datasets[0].data = requests;
                activityChart.data.datasets[1].data = tokens;
                activityChart.update();
            }
        }
        
        document.getElementById('addTextInput').addEventListener('click', () => {
            const container = document.getElementById('textInputsContainer');
            if (container.children.length >= 10) {
                alert('Maximum 10 text inputs allowed');
                return;
            }
            const newGroup = container.firstElementChild.cloneNode(true);
            newGroup.querySelector('textarea').value = '';
            newGroup.querySelector('.remove-input').classList.remove('hidden');
            container.appendChild(newGroup);
            updateRemoveButtons();
        });

        document.getElementById('textInputsContainer').addEventListener('click', function(e) {
            if (e.target.closest('.remove-input')) {
                e.target.closest('.text-input-group').remove();
                updateRemoveButtons();
            }
        });

        function updateRemoveButtons() {
            const groups = document.querySelectorAll('.text-input-group');
            groups.forEach(group => {
                group.querySelector('.remove-input').classList.toggle('hidden', groups.length <= 1);
            });
        }

        document.getElementById('clearBtn').addEventListener('click', () => {
            document.getElementById('apiTestForm').reset();
            const container = document.getElementById('textInputsContainer');
            container.innerHTML = container.firstElementChild.outerHTML;
            container.querySelector('textarea').value = '';
            updateRemoveButtons();
            document.getElementById('resultsSection').classList.add('hidden');
        });

        document.getElementById('apiTestForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const apiKey = document.getElementById('apiKey').value;
            if (!apiKey) { alert('Please enter your API key'); return; }
            
            const texts = Array.from(document.querySelectorAll('#textInputsContainer textarea'))
                                .map(t => t.value.trim()).filter(Boolean);
            if (texts.length === 0) { alert('Please enter at least one text to analyze'); return; }
            
            const analyzeBtn = document.getElementById('analyzeBtn');
            const originalBtnContent = analyzeBtn.innerHTML;
            analyzeBtn.innerHTML = '<div class="loading-spinner inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full mr-2"></div> Analyzing...';
            analyzeBtn.disabled = true;
            
            const startTime = Date.now();
            
            try {
                const response = await fetch('/v1/moderations', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + apiKey },
                    body: JSON.stringify({ input: texts.length === 1 ? texts[0] : texts })
                });
                
                const responseTime = Date.now() - startTime;
                
                const data = await response.json();
                if (!response.ok) throw new Error(data.error || 'Failed to analyze text');
                
                displayResults(data, responseTime, texts);
                fetchMetrics();
                
            } catch (error) {
                alert('Error: ' + error.message);
            } finally {
                analyzeBtn.innerHTML = originalBtnContent;
                analyzeBtn.disabled = false;
            }
        });

        function displayResults(data, responseTime, texts) {
            const resultsSection = document.getElementById('resultsSection');
            const resultsContainer = document.getElementById('resultsContainer');
            
            document.getElementById('responseTime').textContent = responseTime + 'ms';
            resultsContainer.innerHTML = '';
            
            data.results.forEach((result, index) => {
                const resultCard = document.createElement('div');
                resultCard.className = 'border border-gray-200 dark:border-gray-700 rounded-lg p-4';
                
                const flaggedBadge = result.flagged 
                    ? '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-100"><i class="fas fa-exclamation-triangle mr-1"></i> Flagged</span>'
                    : '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100"><i class="fas fa-check-circle mr-1"></i> Safe</span>';
                
                let categoriesHtml = Object.entries(result.category_scores).map(([category, score]) => {
                    const isFlagged = result.categories[category];
                    const categoryClass = isFlagged ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400';
                    const scoreClass = score > 0.7 ? 'text-red-600 dark:text-red-400' : score > 0.4 ? 'text-yellow-600 dark:text-yellow-400' : 'text-green-600 dark:text-green-400';
                    return `
                        <div class="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700 last:border-b-0">
                            <span class="font-medium capitalize">${category.replace(/_/g, ' ')}</span>
                            <div class="flex items-center">
                                <span class="text-sm ${scoreClass} font-mono">${score.toFixed(4)}</span>
                            </div>
                        </div>
                    `;
                }).join('');
                
                resultCard.innerHTML = `
                    <div class="flex justify-between items-start mb-3">
                        <h4 class="text-lg font-semibold">Input ${index + 1}</h4>
                        ${flaggedBadge}
                    </div>
                    <blockquote class="mb-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg text-sm border-l-4 border-gray-300 dark:border-gray-500">${texts[index]}</blockquote>
                    <div class="category-card">
                        <h5 class="font-medium mb-2">Category Scores</h5>
                        <div class="bg-white dark:bg-gray-800/50 rounded-lg p-2">
                            ${categoriesHtml}
                        </div>
                    </div>
                `;
                resultsContainer.appendChild(resultCard);
            });
            
            resultsSection.classList.remove('hidden');
            resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        document.addEventListener('DOMContentLoaded', () => {
            initActivityChart();
            document.getElementById('refreshMetrics').addEventListener('click', fetchMetrics);
            fetchMetrics();
            setInterval(fetchMetrics, 15000);
        });
    </script>
</body>
</html>
''')

if __name__ == '__main__':
    create_directories_and_files()
    port = int(os.getenv('PORT', 7860))
    app.run(host='0.0.0.0', port=port, debug=True, use_reloader=False)