File size: 23,374 Bytes
fe15d80
 
 
 
 
 
 
1be431a
 
 
 
 
42fb43c
1be431a
 
 
 
 
 
 
 
 
fe15d80
d176253
 
 
d53b62d
6af6f76
231a868
fffd7f2
038d754
67f4199
 
f6a92d7
fffd7f2
fe15d80
6af6f76
d176253
 
 
fe15d80
d176253
 
 
 
 
 
fe15d80
1be431a
 
 
 
 
6d6d84c
1be431a
 
 
 
 
 
 
 
 
 
 
 
206753b
038d754
 
1be431a
 
fffd7f2
 
1be431a
 
 
 
 
 
 
 
6d6d84c
1be431a
 
6d6d84c
1be431a
 
 
 
 
 
 
 
 
fffd7f2
 
fe15d80
1be431a
c7ad932
1be431a
 
 
 
fffd7f2
 
 
1be431a
 
 
 
 
 
 
 
038d754
 
 
 
 
 
fe15d80
 
1be431a
67f4199
 
 
 
 
 
 
 
 
 
fe15d80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a92d7
 
 
fffd7f2
 
 
1be431a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe15d80
1be431a
 
 
 
 
 
 
 
 
 
 
 
 
c7ad932
 
 
 
 
 
 
 
 
 
 
1be431a
c7ad932
1be431a
 
 
 
 
 
 
 
 
 
c7ad932
 
fe15d80
c7ad932
1be431a
 
fe15d80
 
 
1be431a
 
 
 
 
 
 
fffd7f2
 
1be431a
 
fe15d80
1be431a
 
 
72fe634
1be431a
9545dbd
147e661
fe15d80
 
 
1be431a
fe15d80
 
 
147e661
fe15d80
 
 
1be431a
d53b62d
 
fe15d80
 
 
 
d53b62d
cf6e402
 
 
 
fe15d80
1be431a
566b7f7
 
fe15d80
566b7f7
1be431a
fe15d80
dd505ce
fe15d80
 
dd505ce
1be431a
fe15d80
16a43bc
 
 
6af6f76
fe15d80
 
 
 
 
 
 
6af6f76
 
 
fe15d80
 
 
a17017c
c10af95
fe15d80
 
a17017c
c10af95
fe15d80
6af6f76
 
 
fe15d80
 
6af6f76
 
 
 
fe15d80
 
 
 
 
 
6af6f76
 
 
fe15d80
6af6f76
fe15d80
 
 
 
 
 
6af6f76
 
 
 
fe15d80
6af6f76
 
fe15d80
 
 
 
 
 
6af6f76
 
 
 
 
 
 
 
 
 
 
 
fe15d80
 
 
 
 
 
65029fb
 
 
6af6f76
fe15d80
d53b62d
20f67e4
 
fe15d80
 
 
 
 
 
 
20f67e4
 
fe15d80
 
 
 
20f67e4
6af6f76
fe15d80
1be431a
20f67e4
 
 
fe15d80
 
 
 
 
20f67e4
 
 
 
 
1be431a
fe15d80
1be431a
20f67e4
 
 
fe15d80
 
 
 
 
20f67e4
 
 
 
 
1be431a
fe15d80
6d6d84c
fe15d80
6af6f76
 
fe15d80
 
 
 
 
 
 
 
 
a17017c
 
fe15d80
6af6f76
fe15d80
a17017c
 
 
6af6f76
 
 
 
 
 
 
 
fe15d80
038d754
6af6f76
2da9742
fe15d80
6af6f76
25a20c0
fe15d80
1be431a
 
 
fe15d80
6d6d84c
 
 
fe15d80
c38b78d
 
 
 
1be431a
fe15d80
1be431a
 
6d6d84c
 
1be431a
fd45959
1be431a
 
 
 
 
 
 
 
c38b78d
ee92837
6d6d84c
1be431a
 
 
 
 
 
 
 
 
8dcf476
fe15d80
d53b62d
fe15d80
1be431a
fe15d80
 
 
 
 
 
1be431a
 
 
 
 
fe15d80
16a43bc
fe15d80
 
 
 
 
 
 
1be431a
4ffd446
 
 
 
 
 
 
 
d176253
 
fe15d80
 
 
d176253
 
8dcf476
d176253
 
 
 
 
 
fe15d80
d176253
 
 
 
 
 
 
 
 
fe15d80
d176253
 
 
 
fe15d80
 
 
 
 
 
d176253
 
 
fe15d80
 
 
d176253
 
fe15d80
 
 
d176253
 
 
fe15d80
d176253
 
 
 
fe15d80
d176253
 
 
 
 
 
fe15d80
 
 
 
 
 
 
 
d176253
 
 
 
 
 
fe15d80
 
d176253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be431a
 
3f7f887
1be431a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2da9742
1be431a
 
 
3f7f887
1be431a
 
4ffd446
 
 
fe15d80
 
 
4ffd446
fe15d80
16a43bc
 
1be431a
 
fe15d80
 
 
 
1be431a
fe15d80
 
 
6d6d84c
 
d176253
6d6d84c
 
8dcf476
d53b62d
 
 
 
 
6d6d84c
 
 
 
 
 
1be431a
 
 
 
 
fe15d80
fd45959
fe15d80
 
 
 
 
 
1be431a
 
 
 
 
d53b62d
 
1be431a
 
 
 
 
 
 
 
 
 
 
16a43bc
1be431a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42f39c4
1be431a
 
 
 
 
 
 
 
 
d176253
 
fe15d80
d176253
16a43bc
1be431a
 
6d6d84c
 
1be431a
fd45959
1be431a
 
 
 
 
 
 
 
 
 
 
 
8dcf476
fe15d80
1be431a
 
 
 
 
 
6d6d84c
1be431a
 
 
 
 
 
 
d53b62d
 
 
 
 
 
 
1be431a
e611170
1be431a
6d6d84c
1be431a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d176253
 
 
 
 
 
 
1be431a
 
fe15d80
 
 
 
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
from utils import (
    cosineSim,
    googleSearch,
    getSentences,
    parallel_scrap,
    matchingScore,
)
import gradio as gr
from urllib.request import urlopen, Request
from googleapiclient.discovery import build
import requests
import httpx
import torch
import re
from bs4 import BeautifulSoup
import numpy as np
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import asyncio
from scipy.special import softmax
from evaluate import load
from datetime import date
import nltk
import fitz
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
import nltk, spacy, subprocess, torch
import plotly.graph_objects as go
import torch.nn.functional as F
import nltk
from unidecode import unidecode
import time
from utils import cos_sim_torch, embed_text
import multiprocessing
from functools import partial
import concurrent.futures

nltk.download("punkt")

from writing_analysis import (
    normalize,
    preprocess_text1,
    preprocess_text2,
    vocabulary_richness_ttr,
    calculate_gunning_fog,
    calculate_average_sentence_length,
    calculate_average_word_length,
    calculate_syntactic_tree_depth,
    calculate_perplexity,
)

np.set_printoptions(suppress=True)


def plagiarism_check(
    plag_option,
    input,
    year_from,
    month_from,
    day_from,
    year_to,
    month_to,
    day_to,
    domains_to_skip,
):
    api_key = "AIzaSyCLyCCpOPLZWuptuPAPSg8cUIZhdEMVf6g"
    api_key = "AIzaSyCS1WQDMl1IMjaXtwSd_2rA195-Yc4psQE"
    api_key = "AIzaSyCB61O70B8AC3l5Kk3KMoLb6DN37B7nqIk"
    # api_key = "AIzaSyCg1IbevcTAXAPYeYreps6wYWDbU0Kz8tg"
    api_key = "AIzaSyA5VVwY1eEoIoflejObrxFDI0DJvtbmgW8"

    cse_id = "851813e81162b4ed4"

    time1 = time.perf_counter()
    start = time.perf_counter()
    sentences = getSentences(input)
    urlCount = {}
    ScoreArray = []
    urlList = []

    date_from = build_date(year_from, month_from, day_from)
    date_to = build_date(year_to, month_to, day_to)
    sort_date = f"date:r:{date_from}:{date_to}"

    # get list of URLS to check
    urlCount, ScoreArray = googleSearch(
        plag_option,
        sentences,
        urlCount,
        ScoreArray,
        urlList,
        sort_date,
        domains_to_skip,
        api_key,
        cse_id,
    )
    print(f"Time for google search: {time.perf_counter()-time1}")
    time1 = time.perf_counter()

    print("Number of URLs: ", len(urlCount))
    print(urlList)

    # Scrape URLs in list
    formatted_tokens = []
    soups = asyncio.run(parallel_scrap(urlList))

    print(f"Time for scraping: {time.perf_counter()-time1}")
    time1 = time.perf_counter()
    print(len(soups))
    print(
        "Successful scraping: "
        + str(len([x for x in soups if x is not None]))
        + "out of "
        + str(len(urlList))
    )

    source_embeddings = []
    for i, soup in enumerate(soups):
        if soup:
            page_content = soup.text
            source_embeddings.append(embed_text(page_content))
        else:
            source_embeddings.append(None)

    # Populate matching scores for scrapped pages
    # for i, soup in enumerate(soups):
    #     print(f"Analyzing {i+1} of {len(soups)} soups........................")
    #     if soup:
    #         page_content = soup.text
    #         for j, sent in enumerate(sentences):
    #             # score = matchingScore(sent, page_content)
    #             # score = matchingScoreWithTimeout(sent, page_content)
    #             score = cos_sim_torch(embed_text(sent), source_embeddings[i])
    #             ScoreArray[i][j] = score

    def compute_cosine_similarity(args):
        sent, source_embedding, i, j = args
        score = cos_sim_torch(embed_text(sent), source_embedding)
        return i, j, score

    def main(soups, sentences):
        source_embeddings = [preprocess(soup) for soup in soups]
        ScoreArray = [[0 for _ in sentences] for _ in soups]
        args_list = []
        for i, soup in enumerate(soups):
            if soup:
                for j, sent in enumerate(sentences):
                    args_list.append((sent, source_embeddings[i], i, j))
        with concurrent.futures.ProcessPoolExecutor() as executor:
            results = executor.map(compute_cosine_similarity, args_list)
            for i, j, score in results:
                ScoreArray[i][j] = score
        return ScoreArray

    ScoreArray = main(soups, sentences)

    print(f"Time for matching score: {time.perf_counter()-time1}")
    time1 = time.perf_counter()

    # ScoreArray = asyncio.run(parallel_analyze_2(soups, sentences, ScoreArray))
    # print("New Score Array:\n")
    # print2D(ScoreArray)

    # Gradio formatting section
    sentencePlag = [False] * len(sentences)
    sentenceToMaxURL = [-1] * len(sentences)
    for j in range(len(sentences)):
        if j > 0:
            maxScore = ScoreArray[sentenceToMaxURL[j - 1]][j]
            sentenceToMaxURL[j] = sentenceToMaxURL[j - 1]
        else:
            maxScore = -1
        for i in range(len(ScoreArray)):
            margin = (
                0.1
                if (j > 0 and sentenceToMaxURL[j] == sentenceToMaxURL[j - 1])
                else 0
            )
            if ScoreArray[i][j] - maxScore > margin:
                maxScore = ScoreArray[i][j]
                sentenceToMaxURL[j] = i
        if maxScore > 0.5:
            sentencePlag[j] = True

    if (
        (len(sentences) > 1)
        and (sentenceToMaxURL[1] != sentenceToMaxURL[0])
        and (
            ScoreArray[sentenceToMaxURL[0]][0]
            - ScoreArray[sentenceToMaxURL[1]][0]
            < 0.1
        )
    ):
        sentenceToMaxURL[0] = sentenceToMaxURL[1]

    index = np.unique(sentenceToMaxURL)

    urlScore = {}
    for url in index:
        s = [
            ScoreArray[url][sen]
            for sen in range(len(sentences))
            if sentenceToMaxURL[sen] == url
        ]
        urlScore[url] = sum(s) / len(s)

    index_descending = sorted(urlScore, key=urlScore.get, reverse=True)

    urlMap = {}
    for count, i in enumerate(index_descending):
        urlMap[i] = count + 1
    for i, sent in enumerate(sentences):
        formatted_tokens.append(
            (sent, "[" + str(urlMap[sentenceToMaxURL[i]]) + "]")
        )

    formatted_tokens.append(("\n", None))
    formatted_tokens.append(("\n", None))
    formatted_tokens.append(("\n", None))

    print(formatted_tokens)
    print(index_descending)

    for ind in index_descending:
        formatted_tokens.append(
            (
                urlList[ind]
                + " --- Matching Score: "
                + f"{str(round(urlScore[ind] * 100, 2))}%",
                "[" + str(urlMap[ind]) + "]",
            )
        )
        formatted_tokens.append(("\n", None))

    print(f"Formatted Tokens: {formatted_tokens}")

    print(f"Time for plagiarism check: {time.perf_counter()-start}")

    return formatted_tokens


"""
AI DETECTION SECTION
"""
device = "cuda" if torch.cuda.is_available() else "cpu"

text_bc_model_path = "polygraf-ai/text-detect-bc-v11-4m"
text_bc_tokenizer = AutoTokenizer.from_pretrained(text_bc_model_path)
text_bc_model = AutoModelForSequenceClassification.from_pretrained(
    text_bc_model_path
).to(device)

text_mc_model_path = (
    "polygraf-ai/ai-text-detection-mc-robert-open-ai-detector-v4"
)
text_mc_tokenizer = AutoTokenizer.from_pretrained(text_mc_model_path)
text_mc_model = AutoModelForSequenceClassification.from_pretrained(
    text_mc_model_path
).to(device)

quillbot_labels = ["Original", "QuillBot"]
quillbot_tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
quillbot_model = AutoModelForSequenceClassification.from_pretrained(
    "polygraf-ai/quillbot-detector-28k"
).to(device)


def remove_accents(input_str):
    text_no_accents = unidecode(input_str)
    return text_no_accents


def remove_special_characters(text):
    text = remove_accents(text)
    pattern = r'[^\w\s\d.,!?\'"()-;]+'
    text = re.sub(pattern, "", text)
    return text


def remove_special_characters_2(text):
    pattern = r"[^a-zA-Z0-9 ]+"
    text = re.sub(pattern, "", text)
    return text


def update_character_count(text):
    return f"{len(text)} characters"


def split_text_allow_complete_sentences_nltk(
    text,
    max_length=256,
    tolerance=30,
    min_last_segment_length=100,
    type_det="bc",
):
    sentences = nltk.sent_tokenize(text)
    segments = []
    current_segment = []
    current_length = 0

    if type_det == "bc":
        tokenizer = text_bc_tokenizer
        max_length = 333

    elif type_det == "mc":
        tokenizer = text_mc_tokenizer
        max_length = 256

    for sentence in sentences:
        tokens = tokenizer.tokenize(sentence)
        sentence_length = len(tokens)

        if current_length + sentence_length <= max_length + tolerance - 2:
            current_segment.append(sentence)
            current_length += sentence_length
        else:
            if current_segment:
                encoded_segment = tokenizer.encode(
                    " ".join(current_segment),
                    add_special_tokens=True,
                    max_length=max_length + tolerance,
                    truncation=True,
                )
                segments.append((current_segment, len(encoded_segment)))
            current_segment = [sentence]
            current_length = sentence_length

    if current_segment:
        encoded_segment = tokenizer.encode(
            " ".join(current_segment),
            add_special_tokens=True,
            max_length=max_length + tolerance,
            truncation=True,
        )
        segments.append((current_segment, len(encoded_segment)))

    final_segments = []
    for i, (seg, length) in enumerate(segments):
        if i == len(segments) - 1:
            if length < min_last_segment_length and len(final_segments) > 0:
                prev_seg, prev_length = final_segments[-1]
                combined_encoded = tokenizer.encode(
                    " ".join(prev_seg + seg),
                    add_special_tokens=True,
                    max_length=max_length + tolerance,
                    truncation=True,
                )
                if len(combined_encoded) <= max_length + tolerance:
                    final_segments[-1] = (prev_seg + seg, len(combined_encoded))
                else:
                    final_segments.append((seg, length))
            else:
                final_segments.append((seg, length))
        else:
            final_segments.append((seg, length))

    decoded_segments = []
    encoded_segments = []
    for seg, _ in final_segments:
        encoded_segment = tokenizer.encode(
            " ".join(seg),
            add_special_tokens=True,
            max_length=max_length + tolerance,
            truncation=True,
        )
        decoded_segment = tokenizer.decode(encoded_segment)
        decoded_segments.append(decoded_segment)
    return decoded_segments


def predict_quillbot(text):
    with torch.no_grad():
        quillbot_model.eval()
        tokenized_text = quillbot_tokenizer(
            text,
            padding="max_length",
            truncation=True,
            max_length=256,
            return_tensors="pt",
        ).to(device)
        output = quillbot_model(**tokenized_text)
        output_norm = softmax(output.logits.detach().cpu().numpy(), 1)[0]
        q_score = {
            "QuillBot": output_norm[1].item(),
            "Original": output_norm[0].item(),
        }
        return q_score


def predict_bc(model, tokenizer, text):
    with torch.no_grad():
        model.eval()
        tokens = text_bc_tokenizer(
            text,
            padding="max_length",
            truncation=True,
            max_length=333,
            return_tensors="pt",
        ).to(device)
        output = model(**tokens)
        output_norm = softmax(output.logits.detach().cpu().numpy(), 1)[0]
        print("BC Score: ", output_norm)
        return output_norm


def predict_mc(model, tokenizer, text):
    with torch.no_grad():
        model.eval()
        tokens = text_mc_tokenizer(
            text,
            padding="max_length",
            truncation=True,
            return_tensors="pt",
            max_length=256,
        ).to(device)
        output = model(**tokens)
        output_norm = softmax(output.logits.detach().cpu().numpy(), 1)[0]
        print("MC Score: ", output_norm)
        return output_norm


def ai_generated_test(ai_option, input):

    bc_scores = []
    mc_scores = []
    samples_len_bc = len(
        split_text_allow_complete_sentences_nltk(input, type_det="bc")
    )
    samples_len_mc = len(
        split_text_allow_complete_sentences_nltk(input, type_det="mc")
    )
    segments_bc = split_text_allow_complete_sentences_nltk(input, type_det="bc")
    segments_mc = split_text_allow_complete_sentences_nltk(input, type_det="bc")

    for i in range(samples_len_bc):
        cleaned_text_bc = remove_special_characters(segments_bc[i])
        bc_score = predict_bc(text_bc_model, text_bc_tokenizer, cleaned_text_bc)
        bc_scores.append(bc_score)

    for i in range(samples_len_mc):
        cleaned_text_mc = remove_special_characters(segments_mc[i])
        mc_score = predict_mc(text_mc_model, text_mc_tokenizer, cleaned_text_mc)
        mc_scores.append(mc_score)

    bc_scores_array = np.array(bc_scores)
    mc_scores_array = np.array(mc_scores)
    average_bc_scores = np.mean(bc_scores_array, axis=0)
    average_mc_scores = np.mean(mc_scores_array, axis=0)
    bc_score_list = average_bc_scores.tolist()
    mc_score_list = average_mc_scores.tolist()

    bc_score = {"AI": bc_score_list[1], "HUMAN": bc_score_list[0]}
    mc_score = {}
    label_map = ["OpenAI GPT", "Mistral", "CLAUDE", "Gemini", "LLAMA 2"]

    for score, label in zip(mc_score_list, label_map):
        mc_score[label.upper()] = score

    sum_prob = 1 - bc_score["HUMAN"]
    for key, value in mc_score.items():
        mc_score[key] = value * sum_prob

    if ai_option == "Human vs AI":
        mc_score = {}

    if sum_prob < 0.01:
        mc_score = {}
        return bc_score, mc_score
    else:
        return bc_score, mc_score


# COMBINED
def main(
    ai_option,
    plag_option,
    input,
    # models,
    year_from,
    month_from,
    day_from,
    year_to,
    month_to,
    day_to,
    domains_to_skip,
):

    formatted_tokens = plagiarism_check(
        plag_option,
        input,
        year_from,
        month_from,
        day_from,
        year_to,
        month_to,
        day_to,
        domains_to_skip,
    )
    depth_analysis_plot = depth_analysis(input)
    bc_score, mc_score = ai_generated_test(ai_option, input)
    quilscore = predict_quillbot(input)

    return (
        bc_score,
        mc_score,
        formatted_tokens,
        depth_analysis_plot,
        quilscore,
    )


def build_date(year, month, day):
    return f"{year}{months[month]}{day}"


def len_validator(text):
    min_tokens = 200
    lengt = len(text_bc_tokenizer.tokenize(text=text, return_tensors="pt"))
    if lengt < min_tokens:
        return f"Warning! Input length is {lengt}. Please input a text that is greater than {min_tokens} tokens long. Recommended length {min_tokens*2} tokens."
    else:
        return f"Input length ({lengt}) is satisified."


def extract_text_from_pdf(pdf_path):
    doc = fitz.open(pdf_path)
    text = ""
    for page in doc:
        text += page.get_text()
    return text


# DEPTH ANALYSIS
print("loading depth analysis")
nltk.download("stopwords")
nltk.download("punkt")
command = ["python3", "-m", "spacy", "download", "en_core_web_sm"]
# Execute the command
subprocess.run(command)
nlp = spacy.load("en_core_web_sm")

# for perplexity
model_id = "gpt2"
gpt2_model = GPT2LMHeadModel.from_pretrained(model_id).to(device)
gpt2_tokenizer = GPT2TokenizerFast.from_pretrained(model_id)


def depth_analysis(input_text):

    # vocanulary richness
    processed_words = preprocess_text1(input_text)
    ttr_value = vocabulary_richness_ttr(processed_words)

    # readability
    gunning_fog = calculate_gunning_fog(input_text)
    gunning_fog_norm = normalize(gunning_fog, min_value=0, max_value=20)

    # average sentence length and average word length
    words, sentences = preprocess_text2(input_text)
    average_sentence_length = calculate_average_sentence_length(sentences)
    average_word_length = calculate_average_word_length(words)
    average_sentence_length_norm = normalize(
        average_sentence_length, min_value=0, max_value=40
    )
    average_word_length_norm = normalize(
        average_word_length, min_value=0, max_value=8
    )

    # syntactic_tree_depth
    average_tree_depth = calculate_syntactic_tree_depth(nlp, input_text)
    average_tree_depth_norm = normalize(
        average_tree_depth, min_value=0, max_value=10
    )

    # perplexity
    perplexity = calculate_perplexity(
        input_text, gpt2_model, gpt2_tokenizer, device
    )
    perplexity_norm = normalize(perplexity, min_value=0, max_value=30)

    features = {
        "readability": gunning_fog_norm,
        "syntactic tree depth": average_tree_depth_norm,
        "vocabulary richness": ttr_value,
        "perplexity": perplexity_norm,
        "average sentence length": average_sentence_length_norm,
        "average word length": average_word_length_norm,
    }

    print(features)

    fig = go.Figure()

    fig.add_trace(
        go.Scatterpolar(
            r=list(features.values()),
            theta=list(features.keys()),
            fill="toself",
            name="Radar Plot",
        )
    )

    fig.update_layout(
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[0, 100],
            )
        ),
        showlegend=False,
        # autosize=False,
        # width=600,
        # height=600,
        margin=dict(
            l=10,
            r=20,
            b=10,
            t=10,
            # pad=100
        ),
    )

    return fig


# START OF GRADIO

title = "Copyright Checker"
months = {
    "January": "01",
    "February": "02",
    "March": "03",
    "April": "04",
    "May": "05",
    "June": "06",
    "July": "07",
    "August": "08",
    "September": "09",
    "October": "10",
    "November": "11",
    "December": "12",
}


with gr.Blocks() as demo:
    today = date.today()
    # dd/mm/YY
    d1 = today.strftime("%d/%B/%Y")
    d1 = d1.split("/")

    model_list = ["OpenAI GPT", "Mistral", "CLAUDE", "Gemini", "LLAMA2"]
    domain_list = ["com", "org", "net", "int", "edu", "gov", "mil"]
    gr.Markdown(
        """
    # Copyright Checker 
    """
    )
    with gr.Row():
        input_text = gr.Textbox(label="Input text", lines=6, placeholder="")
        file_input = gr.File(label="Upload PDF")
        file_input.change(
            fn=extract_text_from_pdf, inputs=file_input, outputs=input_text
        )

    char_count = gr.Textbox(label="Minumum Character Limit Check")
    input_text.change(fn=len_validator, inputs=input_text, outputs=char_count)

    with gr.Row():
        with gr.Column():
            ai_option = gr.Radio(
                ["Human vs AI", "Human vs AI Source Models"],
                label="Choose an option please.",
            )
        with gr.Column():
            plag_option = gr.Radio(
                ["Standard", "Advanced"], label="Choose an option please."
            )

    with gr.Row():
        with gr.Column():
            only_ai_btn = gr.Button("AI Check")

        with gr.Column():
            only_plagiarism_btn = gr.Button("Source Check")

    with gr.Row():
        quillbot_check = gr.Button("Humanized Text Check (Quillbot)")

    with gr.Row():
        depth_analysis_btn = gr.Button("Detailed Writing Analysis")

    with gr.Row():
        full_check_btn = gr.Button("Full Check")

    gr.Markdown(
        """
        ## Output
        """
    )

    # models = gr.Dropdown(
    # model_list,
    # value=model_list,
    # multiselect=True,
    # label="Models to test against",
    # )

    with gr.Row():
        with gr.Column():
            bcLabel = gr.Label(label="Source")
        with gr.Column():
            mcLabel = gr.Label(label="Creator")
    with gr.Row():
        QLabel = gr.Label(label="Humanized")
    with gr.Group():
        with gr.Row():
            month_from = gr.Dropdown(
                choices=months,
                label="From Month",
                value="January",
                interactive=True,
            )
            day_from = gr.Textbox(label="From Day", value="01")
            year_from = gr.Textbox(label="From Year", value="2000")
            # from_date_button = gr.Button("Submit")

        with gr.Row():
            month_to = gr.Dropdown(
                choices=months,
                label="To Month",
                value=d1[1],
                interactive=True,
            )
            day_to = gr.Textbox(label="To Day", value=d1[0])
            year_to = gr.Textbox(label="To Year", value=d1[2])
            # to_date_button = gr.Button("Submit")
        with gr.Row():
            domains_to_skip = gr.Dropdown(
                domain_list,
                multiselect=True,
                label="Domain To Skip",
            )

    with gr.Row():
        with gr.Column():
            sentenceBreakdown = gr.HighlightedText(
                label="Source Detection Sentence Breakdown",
                combine_adjacent=True,
                color_map={
                    "[1]": "red",
                    "[2]": "orange",
                    "[3]": "yellow",
                    "[4]": "green",
                },
            )

    with gr.Row():
        with gr.Column():
            writing_analysis_plot = gr.Plot(label="Writing Analysis Plot")

    full_check_btn.click(
        fn=main,
        inputs=[
            ai_option,
            plag_option,
            input_text,
            # models,
            year_from,
            month_from,
            day_from,
            year_to,
            month_to,
            day_to,
            domains_to_skip,
        ],
        outputs=[
            bcLabel,
            mcLabel,
            sentenceBreakdown,
            writing_analysis_plot,
            QLabel,
        ],
        api_name="main",
    )

    only_ai_btn.click(
        fn=ai_generated_test,
        inputs=[ai_option, input_text],
        outputs=[
            bcLabel,
            mcLabel,
        ],
        api_name="ai_check",
    )

    quillbot_check.click(
        fn=predict_quillbot,
        inputs=[input_text],
        outputs=[QLabel],
        api_name="quillbot_check",
    )

    only_plagiarism_btn.click(
        fn=plagiarism_check,
        inputs=[
            plag_option,
            input_text,
            year_from,
            month_from,
            day_from,
            year_to,
            month_to,
            day_to,
            domains_to_skip,
        ],
        outputs=[
            sentenceBreakdown,
        ],
        api_name="plagiarism_check",
    )

    depth_analysis_btn.click(
        fn=depth_analysis,
        inputs=[input_text],
        outputs=[writing_analysis_plot],
        api_name="depth_analysis",
    )

    date_from = ""
    date_to = ""

demo.launch(
    share=True, server_name="0.0.0.0", auth=("polygraf-admin", "test@aisd")
)