File size: 11,099 Bytes
20be0fa
ecdb175
3ef7501
 
4d2cd01
 
 
 
 
 
 
fa4f2b7
7a02768
 
 
 
 
 
 
 
 
 
ecdb175
 
 
 
 
 
 
 
 
721c502
ecdb175
 
7a02768
ecdb175
 
 
 
 
77f8cb9
7a02768
77f8cb9
 
 
 
 
721c502
7a02768
721c502
7a02768
170516a
721c502
 
7a02768
 
170516a
 
 
 
 
 
 
 
 
 
 
 
 
ecdb175
7a02768
 
 
 
ecdb175
77f8cb9
3ef7501
fa4f2b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d2cd01
77f8cb9
20be0fa
7a02768
 
 
 
 
 
 
5519f66
7a02768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170516a
 
7a02768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633c7f5
7a02768
 
721c502
7a02768
 
f08423d
7a02768
 
f08423d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633c7f5
fa4f2b7
20be0fa
170516a
20be0fa
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
import streamlit as st
import random
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
import torch
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from docx import Document

# --- Streamlit Page Configuration ---
st.set_page_config(page_title="AI & Plagiarism Detection", page_icon="πŸ”", layout="wide")

# --- DeepSeek Theme ---
DEEPSEEK_THEME = {
    "backgroundColor": "#282c34",
    "textColor": "#abb2bf",
    "inputAreaColor": "#3E4451",
    "accentColor": "#61afef",
    "sidebarColor": "#21252b",
    "font": "sans-serif",
}

# --- Function to Apply Theme ---
def apply_theme(theme):
    st.markdown(f"""
        <style>
            body {{
                color: {theme["textColor"]};
                background-color: {theme["backgroundColor"]};
                font-family: {theme["font"]};
            }}
            .welcome-text {{
                color: {theme["textColor"]};
                font-size: 36px;
                font-weight: bold;
                text-align: center;
                margin-bottom: 20px;
            }}
            .output-box {{
                background-color: {theme["inputAreaColor"]};
                color: {theme["textColor"]};
                padding: 10px;
                border-radius: 5px;
                margin-top: 20px;
            }}
            .stTextArea textarea {{
                background-color: {theme["inputAreaColor"]};
                color: {theme["textColor"]};
                border: 1px solid {theme["accentColor"]};
                border-radius: 5px;
            }}
            .stFileUploader > div > div:nth-child(1) > div > button {{
                background-color: {theme["accentColor"]};
                color: {theme["backgroundColor"]};
                border-radius: 5px;
            }}
            .stMetricLabel {{
                color: {theme["textColor"]} !important;
            }}
            .stMetricValue {{
                color: {theme["textColor"]} !important;
            }}
            .streamlit-expanderHeader {{
                color: {theme["textColor"]};
            }}
            .streamlit-expanderContent {{
                color: {theme["textColor"]};
            }}
            [data-testid="stSidebar"] {{
                background-color: {theme["sidebarColor"]};
                color: {theme["textColor"]};
            }}
        </style>
    """, unsafe_allow_html=True)

# --- Helper Functions ---
def extract_text_from_pdf(pdf_file):
    resource_manager = PDFResourceManager()
    output_string = io.StringIO()
    laparams = LAParams()
    device = TextConverter(resource_manager, output_string, laparams=laparams)
    interpreter = PDFPageInterpreter(resource_manager, device)

    for page in PDFPage.get_pages(pdf_file, caching=True, check_extractable=True):
        interpreter.process_page(page)
    text = output_string.getvalue()
    device.close()
    output_string.close()
    return text

def extract_text_from_docx(docx_file):
    doc = Document(docx_file)
    full_text = []
    for paragraph in doc.paragraphs:
        full_text.append(paragraph.text)
    return '\n'.join(full_text)

def split_text_into_chunks(text, tokenizer, max_length=512):
    chunks = []
    tokens = tokenizer.tokenize(text)
    for i in range(0, len(tokens), max_length):
        chunk_tokens = tokens[i:i + max_length]
        chunk_text = tokenizer.convert_tokens_to_string(chunk_tokens)
        chunks.append(chunk_text)
    return chunks

@st.cache_resource
def load_ai_detection_model(model_name="Hello-SimpleAI/chatgpt-detector-roberta"):
    try:
        ai_detection = pipeline("text-classification", model=model_name, truncation=True, max_length=512)
        return ai_detection
    except Exception as e:
        st.error(f"Error loading AI detection model: {e}")
        return None

@st.cache_resource
def load_plagiarism_model(model_name="jpwahle/longformer-base-plagiarism-detection"):
    try:
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        model = AutoModelForSequenceClassification.from_pretrained(model_name)
        return tokenizer, model
    except Exception as e:
        st.error(f"Error loading plagiarism detection model: {e}")
        return None

def detect_ai_content(text_chunks, ai_detection_model, ai_threshold=0.4):
    try:
        ai_percentages = []
        for chunk in text_chunks:
            result = ai_detection_model(chunk)
            ai_label = result[0]['label']
            ai_score = result[0]['score']

            if ai_label == 'AI' and ai_score > ai_threshold:
                ai_percentages.append(ai_score)
            elif ai_label == 'Human' and ai_score < (1 - ai_threshold):
                ai_percentages.append(0)
            else:
                ai_percentages.append(0)

        return ai_percentages
    except Exception as e:
        st.error(f"Error during AI content detection: {e}")
        return None

def plagiarism_check(text_chunks, tokenizer, model):
    try:
        plagiarized_count = 0
        for chunk in text_chunks:
            inputs = tokenizer(chunk, return_tensors="pt", truncation=True, padding=True, max_length=512)
            with torch.no_grad():
                outputs = model(**inputs)
                predicted_class = torch.argmax(outputs.logits, dim=-1).item()
                if predicted_class == 1:
                    plagiarized_count += 1

        plagiarism_percentage = (plagiarized_count / len(text_chunks)) * 100
        return plagiarism_percentage
    except Exception as e:
        st.error(f"Error during plagiarism detection: {e}")
        return None

# --- Main Function ---
def main():
    # --- Apply DeepSeek Theme ---
    apply_theme(DEEPSEEK_THEME)

    # --- Sidebar ---
    with st.sidebar:
        st.markdown("<h1 style='color:#61afef;'>AI & Plagiarism</h1>", unsafe_allow_html=True)
        st.markdown("Navigation")
        menu_options = ["New Chat"]  # Removed "My Profile" and "Get App"
        selected_option = st.radio("Choose an option", menu_options)
        st.markdown("---")

        st.markdown("Today")
        recent_chats = ["Chat 1", "Chat 2", "Chat 3"]
        for chat in recent_chats:
            st.markdown(f"- {chat}")

    # --- Main Content ---
    col1, col2 = st.columns([1, 3])  # Adjust the ratio as needed

    with col2:
        st.markdown("<h1 class='welcome-text'>Hi, I'm AI & Plagiarism Assistant.</h1>", unsafe_allow_html=True)
        st.markdown("How can I help you today?")

        # --- Input Area: Text Area and File Upload ---
        input_text = st.text_area("Message", "", height=200)
        uploaded_files = st.file_uploader("Attach documents (PDF or DOCX)", type=["pdf", "docx"], accept_multiple_files=True)

        # --- Load models ---
        ai_detection_model, tokenizer, plagiarism_model = load_models()

        # --- Process Input ---
        if input_text or uploaded_files:
            raw_text = ""

            # --- Process Uploaded Files ---
            if uploaded_files:
                with st.expander("Uploaded Files", expanded=False):
                    for uploaded_file in uploaded_files:
                        file_size = len(uploaded_file.getvalue())
                        if file_size > 1000000000:
                            st.error(f"{uploaded_file.name}: File size exceeds the 1GB limit.")
                            continue

                        try:
                            if uploaded_file.type == "application/pdf":
                                extracted_text = extract_text_from_pdf(uploaded_file)
                                raw_text += extracted_text + "\n"
                                st.write(f"Extracted text from {uploaded_file.name}")
                            elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                                extracted_text = extract_text_from_docx(uploaded_file)
                                raw_text += extracted_text + "\n"
                                st.write(f"Extracted text from {uploaded_file.name}")
                            else:
                                st.error(f"{uploaded_file.name}: Unsupported file type")
                                continue

                        except Exception as e:
                            st.error(f"Error processing {uploaded_file.name}: {e}")
                            continue

            # --- Append Manual Text ---
            raw_text += input_text.strip()

            # --- Split text into manageable chunks ---
            text_chunks = split_text_into_chunks(raw_text.strip(), tokenizer)

            # --- Process and Display Results ---
            process_and_display(text_chunks, "Combined Input", ai_detection_model, tokenizer, plagiarism_model)

# --- Helper function to process text and display results ---
def process_and_display(text_chunks, source_name, ai_detection_model, tokenizer, plagiarism_model):
    # AI Detection
    ai_percentage_avg = None
    human_percentage = None
    if ai_detection_model:
        ai_percentages = detect_ai_content(text_chunks, ai_detection_model)
        if ai_percentages:
            ai_percentage_avg = sum(ai_percentages) / len(ai_percentages) * 100
            human_percentage = 100 - ai_percentage_avg

    # Plagiarism Check
    plagiarism_percentage = None
    if tokenizer and plagiarism_model:
        plagiarism_percentage = plagiarism_check(text_chunks, tokenizer, plagiarism_model)

    # --- Tiled Output ---
    with st.container():
        st.markdown(f"<div class='output-box'><h3>{source_name}</h3></div>", unsafe_allow_html=True)

        col1, col2 = st.columns(2)

        with col1:
            st.markdown("<div class='output-box'><h4>AI Detection:</h4></div>", unsafe_allow_html=True)
            if ai_percentage_avg is not None:
                st.metric(label="AI Content", value=f"{ai_percentage_avg:.2f}%", delta="AI Generated")
                st.metric(label="Human Written", value=f"{human_percentage:.2f}%", delta="Humanized Text")
            else:
                st.write("AI Detection not available")

        with col2:
            st.markdown("<div class='output-box'><h4>Plagiarism Detection:</h4></div>", unsafe_allow_html=True)
            if plagiarism_percentage is not None:
                st.metric(label="Plagiarism", value=f"{plagiarism_percentage:.2f}%", delta="Plagiarized" if plagiarism_percentage > 0 else "Original")
            else:
                st.write("Plagiarism Detection not available")

# --- Load models globally ---
@st.cache_resource
def load_models():
    ai_detection_model = load_ai_detection_model()
    tokenizer, plagiarism_model = load_plagiarism_model()
    return ai_detection_model, tokenizer, plagiarism_model

# --- Call Main ---
if __name__ == "__main__":
    ai_detection_model, tokenizer, plagiarism_model = load_models()
    main()