TRACES commited on
Commit
ea0ff68
0 Parent(s):

Duplicate from TRACES/streamlit-test

Browse files
.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ <<<<<<< HEAD
36
+ *.pk filter=lfs diff=lfs merge=lfs -text
37
+ =======
38
+ >>>>>>> 534a2fcfb5d15432348f76ee7edeceaae194bef9
.streamlit/config.toml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ [server]
2
+ # The port where the server will listen for browser connections.
3
+ # Default: 8501
4
+ # port = 7860
5
+
6
+ [browser]
7
+ # Port where users should point their browsers in order to connect to the app.
8
+ # This is used to: - Set the correct URL for CORS and XSRF protection purposes. - Show the URL on the terminal - Open the browser
9
+ # Default: whatever value is set in server.port.
10
+ # serverPort = 7860
README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: TRACES
3
+ colorFrom: blue
4
+ colorTo: blue
5
+ sdk: streamlit
6
+ sdk_version: 1.17.0
7
+ app_file: main.py
8
+ duplicated_from: TRACES/streamlit-test
9
+ ---
main.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ import streamlit as st
5
+ import pickle
6
+
7
+ from transformers import AutoTokenizer, BertForSequenceClassification, pipeline
8
+ from sklearn.feature_extraction.text import TfidfVectorizer
9
+
10
+
11
+ def load_models():
12
+ st.session_state.loaded = True
13
+
14
+ with open("models/tfidf_vectorizer_svm_gpt_bg_0.9338_text4.pkl", "rb") as f:
15
+ st.session_state.tfidf_vectorizer = pickle.load(f)
16
+
17
+ with open('models/svm_model_gpt_detection_tfidf_bg_0.9338_text4.pkl', 'rb') as f:
18
+ st.session_state.gpt_detector = pickle.load(f)
19
+
20
+ st.session_state.bert = pipeline(task="text-classification",
21
+ model=BertForSequenceClassification.from_pretrained("TRACES/private-bert", use_auth_token=os.environ['ACCESS_TOKEN'], num_labels=2),
22
+ tokenizer=AutoTokenizer.from_pretrained("TRACES/private-bert", use_auth_token=os.environ['ACCESS_TOKEN']))
23
+
24
+
25
+ def load_content():
26
+ with open('resource/page_content.json', encoding='utf8') as json_file:
27
+ return json.load(json_file)
28
+
29
+
30
+ def switch_lang(lang):
31
+ if 'lang' in st.session_state:
32
+ if lang == 'bg':
33
+ st.session_state.lang = 'bg'
34
+ else:
35
+ st.session_state.lang = 'en'
36
+
37
+
38
+ if 'lang' not in st.session_state:
39
+ st.session_state.lang = 'bg'
40
+
41
+ if 'gpt_detector_result' not in st.session_state and 'bert_result' not in st.session_state:
42
+ st.session_state.gpt_detector_result = ''
43
+ st.session_state.gpt_detector_probability = [1, 0]
44
+ st.session_state.bert_result = [{'label': '', 'score': 1}]
45
+
46
+ content = load_content()
47
+ if 'loaded' not in st.session_state:
48
+ load_models()
49
+
50
+ #######################################################################################################################
51
+
52
+ st.title(content['title'][st.session_state.lang])
53
+
54
+ col1, col2, col3 = st.columns([1, 1, 10])
55
+ with col1:
56
+ st.button(
57
+ label='EN',
58
+ key='en',
59
+ on_click=switch_lang,
60
+ args=['en']
61
+ )
62
+ with col2:
63
+ st.button(
64
+ label='BG',
65
+ key='bg',
66
+ on_click=switch_lang,
67
+ args=['bg']
68
+ )
69
+
70
+ if 'agree' not in st.session_state:
71
+ st.session_state.agree = False
72
+
73
+ if st.session_state.agree:
74
+ tab_tool, tab_terms = st.tabs([content['tab_tool'][st.session_state.lang], content['tab_terms'][st.session_state.lang]])
75
+
76
+ with tab_tool:
77
+ user_input = st.text_area(content['textbox_title'][st.session_state.lang],
78
+ content['text_placeholder'][st.session_state.lang]).strip('\n')
79
+
80
+ if st.button(content['analyze_button'][st.session_state.lang]):
81
+ user_tfidf = st.session_state.tfidf_vectorizer.transform([user_input])
82
+
83
+ st.session_state.gpt_detector_result = st.session_state.gpt_detector.predict(user_tfidf)[0]
84
+ st.session_state.gpt_detector_probability = st.session_state.gpt_detector.predict_proba(user_tfidf)[0]
85
+ st.session_state.bert_result = st.session_state.bert(user_input)
86
+
87
+ if st.session_state.gpt_detector_result == 1:
88
+ st.warning(content['gpt_getect_yes'][st.session_state.lang] +
89
+ str(round(st.session_state.gpt_detector_probability[1] * 100, 2)) +
90
+ content['gpt_yes_proba'][st.session_state.lang], icon="⚠️")
91
+ else:
92
+ st.success(content['gpt_getect_no'][st.session_state.lang] +
93
+ str(round(st.session_state.gpt_detector_probability[0] * 100, 2)) +
94
+ content['gpt_no_proba'][st.session_state.lang], icon="✅")
95
+
96
+ if st.session_state.bert_result[0]['label'] == 'LABEL_1':
97
+ st.warning(content['bert_yes_1'][st.session_state.lang] +
98
+ str(round(st.session_state.bert_result[0]['score'] * 100, 2)) +
99
+ content['bert_yes_2'][st.session_state.lang], icon = "⚠️")
100
+ else:
101
+ st.success(content['bert_no_1'][st.session_state.lang] +
102
+ str(round(st.session_state.bert_result[0]['score'] * 100, 2)) +
103
+ content['bert_no_2'][st.session_state.lang], icon="✅")
104
+
105
+ st.info(content['disinformation_definition'][st.session_state.lang], icon="ℹ️")
106
+
107
+ with tab_terms:
108
+ st.write(content['disclaimer'][st.session_state.lang])
109
+
110
+ else:
111
+ st.write(content['disclaimer_title'][st.session_state.lang])
112
+ st.write(content['disclaimer'][st.session_state.lang])
113
+ if st.button(content['disclaimer_agree_text'][st.session_state.lang]):
114
+ st.session_state.agree = True
115
+ st.experimental_rerun()
models/svm_model_gpt_detection_tfidf_bg_0.9338_text4.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3206869ce5f2dc90c474b84a1e62196d670961e77dc776b58fae5b10fa48eef9
3
+ size 467467
models/tfidf_vectorizer_svm_gpt_bg_0.9338_text4.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6bf9391c5866c29bc45051c63efec406a4a613aada1a10a3fa51992ddd6a19b
3
+ size 525728
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
1
+ scipy
2
+ transformers
3
+ pickle-mixin
4
+ streamlit
5
+ scikit-learn
6
+ torch
resource/page_content.json ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "title": {
3
+ "bg": "Инструмент за разпознаване на дезинформация и текстови дийпфейкове",
4
+ "en": "Tool for recognizing disinformation and deepfake texts"
5
+ },
6
+ "disclaimer_title": {
7
+ "bg": "Моля, запознайте се с условията за ползване",
8
+ "en": "Please read the terms of use"
9
+ },
10
+ "disclaimer_agree_text": {
11
+ "bg": "Запознат съм с условията на ползване",
12
+ "en": "I agree"
13
+ },
14
+ "disclaimer": {
15
+ "bg": "Моля, прочетете целия текст. Достъпът до уеб инструмента ще бъде предоставен само ако сте съгласни с условията за използване, посочени по-долу: \n \n За какво може да се използва този уеб инструмент: \n \n Инструментът използва резултатите от проекта TRACES (https://traces.gate-ai.eu/), който е получил непряко финансиране по Програмата на Европейския съюз за действие в областта на научните изследвания и иновациите “Хоризонт 2020” чрез Открита покана № 1, публикувана и изпълнена в рамките на проекта AI4Media (Договор № 951911).\n \n Целта на този прототип е да дава преценка, дали даден текст потенциално съдържа целенасочена дезинформация или представлява автоматично генериран текст (с цел да се разпознават текстови “дийпфейкове”).\n \n Значението на понятието \"дезинформация\" е взето от Съобщението на Европейската комисия до Европейския парламент, Съвета, Европейския икономически и социален комитет и Комитета на регионите относно Плана за действие за европейска демокрация (https://eur-lex.europa.eu/legal-content/BG/TXT/HTML/?uri=CELEX:52020DC0790&from=EN) и означава \"невярно или подвеждащо съдържание, което се разпространява с цел да заблуди или да се осигури икономическа или политическа изгода и което може да причини обществена вреда\". \n \n Инструментът дава и вероятност (увереността на използвания алгоритъм за машинно обучение), с която може да се твърди, че въведеният текст съдържа дезинформация или представлява автоматично генериран текст (с модела GPT-2). \n \n Моля, имайте предвид следните предупреждения: \n \n 1. Този инструмент е от равнище на технологична готовност 4 (прототип, тестван в лабораторна среда). Като такъв, той не е изпитан в реална среда и не можете да го използвате в такава. \n 2. С цел спазване на законите на България и Европейския съюз, включително тези за правата на човека, уронване на доброто име и клевета, моля, обърнете внимание на следното: \n - Инструментът използва методите на изкуствения интелект, и по-специално машинното обучение. \n - Анализът, извършен от уеб инструмента върху анализираните текстове, може да покаже само потенциалното наличие на дезинформация или на автоматично генерирани текстове (по модела gpt-2). \n - Това указание следва да се приема с по-ниска степен на доверие (\"известна вероятност\", но не и \"сигурност\"). \n - Не следва да се предприемат правни действия срещу авторите на текстове, чиито текстове са идентифицирани от инструмента като съдържащи умишлена дезинформация или представляващи автоматично генерирани текстове, единствено въз основа на резултатите от този инструмент. \n - Използваните методи и резултати не са подходящи за използване за целите на правителствени или публични органи, включително за разследвания, разузнавателна дейност, наказателно разследване, съдебни или административни производства. \n - Прогнозите за потенциална фалшивост/невярност/дезинформация на текстове, които онлайн инструментът предоставя, не са вярвания/твърдения на авторите, изследователите или участниците в проекта. \n - Спонсорите, изследователите, участващи в Проекта, потребителите или субектите на Проекта не носят отговорност и не са обвързани по какъвто и да е било начин с каквито и да било щети (включително имуществени или морални), произтичащи от или във връзка с анализа на уеб инструмента, използвания метод и/или постигнатите резултати/изводи." ,
16
+ "en": "Please read the whole text. You will be given access to the tool only when you agree with the usage conditions below:\n \n What does this tool do: \n \n The tool uses the findings of the TRACES project (https://traces.gate-ai.eu/), which has indirectly received funding from the European Union’s Horizon 2020 research and innovation action programme, via the AI4Media Open Call #1 issued and executed under the AI4Media project (Grant Agreement no. 951911).\n \n The purpose of this prototype tool is to provide an indication of whether a given text in Bulgarian potentially contains intentional disinformation and whether it has been automatically generated (with the aim to recognize textual \"deepfakes\").\n \n The meaning of \"disinformation\" is taken from European Commission's Communication to the European Parliament, the Council, the European Economic and Social Committee, and the Committee of the Regions on the European Democracy Action Plan (https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=COM:2020:790:FIN), and it designs \"false or misleading content that is spread with an intention to deceive or secure economic or political gain and which may cause public harm\". \n \n The tool outputs a probability (the confidence of the machine learning algorithm) with which it could be claimed that an input text contains disinformation or that it is an automatically generated text (by a GPT-2 model). \n \n Please note the following warnings: \n \n 1. This tool is at Technology Readiness Level 4 - Technology validated in lab. It has not been tested in a real environment and thus it should not be used in such. \n 2. In order to comply with Bulgarian and European Union laws, including those on human rights, damage to the reputation, and defamation, please note that: \n - The tool uses Machine Learning (Artificial Intelligence) methods. \n - The analysis run by the web tool on the analyzed texts may show only the potential presence of disinformation or of automatically generated texts (by a gpt-2 model). \n - This indication should be taken with a lower degree of confidence (certain likelihood, but not certainty). \n - No legal action should be taken against the authors of texts, whose texts are identified by the tool as potentially containing intentional disinformation or as potentially representing automatically generated texts, solely based on the results of this tool. \n - The methods used and results obtained are not suitable to be used for governmental or public authority purposes, including for investigations, intelligence work, criminal investigation, court or administrative proceedings. \n - The predictions for potential fakeness/wrongness/disinformation of the texts, which the online tool provides are not statements/beliefs/affirmations of the Project's authors, researchers or participants. \n - The Project Sponsors, Researchers, users or subjects shall not be liable or otherwise responsible for any damages (including pecuniary or moral damages) arising out or in relation to the web tool analysis, the method used and/or the results/outcomes."
17
+ },
18
+ "text_placeholder": {
19
+ "bg": "Това е примерно изречение.",
20
+ "en": "Това е примерно изречение."
21
+ },
22
+ "textbox_title": {
23
+ "bg": "Въведете текст за анализ",
24
+ "en": "Enter text to analyze"
25
+ },
26
+ "analyze_button": {
27
+ "bg": "Анализирай текста",
28
+ "en": "Analyze text"
29
+ },
30
+ "full_result_title": {
31
+ "bg": "Покажи пълен резултат",
32
+ "en": "Show full result"
33
+ },
34
+ "gpt_getect_no": {
35
+ "bg": "Според анализа този те��ст е написан от човек с вероятност: ",
36
+ "en": "Our tool has determined that the input text was generated by a human with "
37
+ },
38
+ "gpt_no_proba": {
39
+ "bg": " %. Препоръчително е да проверите внимателно твърденията в него, преди да им се доверите.",
40
+ "en": "% probability. However, we recommend that you carefully verify its claims."
41
+ },
42
+ "gpt_getect_yes": {
43
+ "bg": "Според анализа този текст е автоматично генериран от модела GPT-2 с вероятност: ",
44
+ "en": "Our tool has determined that this text was automatically generated by the language model GPT-2 with"
45
+ },
46
+ "gpt_yes_proba": {
47
+ "bg": " %. Имайте предвид, че този резултат е базиран на методите на изкуствения интелект и може да бъде грешен. За момента не можем да проверим, дали е верен. Внимателно проверете твърденията в него!",
48
+ "en": "% probability. Note, that this is an AI-based tool and it can make mistakes. Read and check carefully its claims!"
49
+ },
50
+ "bert_yes_1": {
51
+ "bg": "Според анализа, този текст съдържа дезинформация с вероятност: ",
52
+ "en": "According to the analysis, this text contains disinformation with "
53
+ },
54
+ "bert_yes_2": {
55
+ "bg": " %. Имайте предвид, че това са резултати от машинно обучение, и както е написано в условията за ползване, не можете да се доверите напълно на този резултат.",
56
+ "en": " % probability. Keep in mind that these are machine learning results, and as it is written in the Terms of Use, you cannot fully trust this result."
57
+ },
58
+ "bert_no_1": {
59
+ "bg": "Според анализа, този текст не съдържа дезинформация с вероятност: ",
60
+ "en": "According to the analysis, this text does not contain misinformation with "
61
+ },
62
+ "bert_no_2": {
63
+ "bg": " %. Въпреки това е препоръчително да проверите внимателно твърденията в него, преди да им се доверите.",
64
+ "en": " % probability. However, it is advisable to carefully check the claims before you trust them."
65
+ },
66
+ "disinformation_definition": {
67
+ "bg": "Дезинформация наричаме целенасочено разпространявана невярна информация.",
68
+ "en": "Disinformation is false information deliberately spread to deceive people."
69
+ },
70
+ "tab_tool": {
71
+ "bg": "Инструмент",
72
+ "en": "Tool"
73
+ },
74
+ "tab_terms": {
75
+ "bg": "Условия за ползване",
76
+ "en": "Terms and conditions"
77
+ }
78
+ }