abdurrehmansaeed commited on
Commit
b9cb33d
·
verified ·
1 Parent(s): 173df96

Upload 7 files

Browse files
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ RUN apt-get update && apt-get install -y \
4
+ libgl1 \
5
+ libglib2.0-0 \
6
+ && rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+
10
+ COPY requirements.txt .
11
+ RUN pip install --no-cache-dir --upgrade pip && \
12
+ pip install --no-cache-dir -r requirements.txt
13
+
14
+
15
+ COPY . .
16
+ EXPOSE 7860
17
+
18
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ import torch
3
+ from transformers import DistilBertTokenizer, DistilBertModel
4
+ import os
5
+ from PIL import Image
6
+ import io
7
+ import base64
8
+ import torch.nn as nn
9
+ from torchvision import models
10
+ from huggingface_hub import InferenceClient
11
+ import string
12
+ import nltk
13
+ from nltk.sentiment.vader import SentimentIntensityAnalyzer
14
+ import numpy as np
15
+
16
+ # Download NLTK data
17
+ nltk.download('vader_lexicon')
18
+
19
+ # Define the DistilBERT+ResNet model class
20
+ class ExactDistilBertResNetModel(nn.Module):
21
+ def __init__(self, num_classes=2):
22
+ super(ExactDistilBertResNetModel, self).__init__()
23
+
24
+ # DistilBERT component
25
+ self.distilbert = DistilBertModel.from_pretrained('distilbert-base-uncased')
26
+ distilbert_output_dim = 768 # DistilBERT hidden size
27
+
28
+ # ResNet component - without the final FC layer
29
+ self.resnet = models.resnet18(weights=None)
30
+ self.resnet.fc = nn.Identity() # Remove the final fully connected layer
31
+
32
+ self.metadata_fc = nn.Linear(6, 32)
33
+
34
+ # Combined classifier
35
+ self.classifier = nn.Sequential(
36
+ nn.Linear(1312, 128),
37
+ nn.ReLU(),
38
+ nn.Dropout(0.1),
39
+ nn.Linear(128, num_classes)
40
+ )
41
+
42
+ def forward(self, input_ids=None, attention_mask=None, metadata=None):
43
+ # Process text with DistilBERT
44
+ distilbert_outputs = self.distilbert(
45
+ input_ids=input_ids,
46
+ attention_mask=attention_mask
47
+ )
48
+ # Get the [CLS] token output (text representation)
49
+ text_features = distilbert_outputs.last_hidden_state[:, 0, :] # Shape: [batch_size, 768]
50
+
51
+ # Process metadata features
52
+ if metadata is not None:
53
+ metadata_features = self.metadata_fc(metadata) # Shape: [batch_size, 32]
54
+ else:
55
+ batch_size = text_features.shape[0]
56
+ metadata_features = torch.zeros(batch_size, 32, device=text_features.device)
57
+
58
+ # Placeholder for ResNet features (512 dimensions)
59
+ batch_size = text_features.shape[0]
60
+ other_features = torch.zeros(batch_size, 512, device=text_features.device)
61
+
62
+ # Combine features
63
+ combined_features = torch.cat([text_features, metadata_features, other_features], dim=1)
64
+
65
+ # Final classification
66
+ logits = self.classifier(combined_features)
67
+ return logits
68
+
69
+ app = Flask(__name__)
70
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload
71
+
72
+ # Initialize Hugging Face Inference Client
73
+ def initialize_inference_client():
74
+ try:
75
+ client = InferenceClient(
76
+ provider="nebius",
77
+ api_key=os.environ.get("HF_TOKEN"),
78
+ )
79
+ print("Hugging Face Inference Client initialized successfully")
80
+ return client
81
+ except Exception as e:
82
+ print(f"Error initializing Hugging Face Inference Client: {e}")
83
+ return None
84
+
85
+ # Extract text-based metadata features (6 features)
86
+ def extract_text_features(review_text):
87
+ # Initialize sentiment analyzer
88
+ sid = SentimentIntensityAnalyzer()
89
+
90
+ # 1. Review Length (number of characters)
91
+ review_length = len(review_text)
92
+
93
+ # 2. Sentiment (compound score from VADER)
94
+ sentiment = sid.polarity_scores(review_text)['compound']
95
+
96
+ # 3. Punctuation Count
97
+ punctuation_count = sum(1 for char in review_text if char in string.punctuation)
98
+
99
+ # 4. Average Word Length
100
+ words = review_text.split()
101
+ avg_word_length = np.mean([len(word) for word in words]) if words else 0
102
+
103
+ # 5. Capitalization Ratio
104
+ capital_letters = sum(1 for char in review_text if char.isupper())
105
+ capitalization_ratio = capital_letters / len(review_text) if review_text else 0
106
+
107
+ # 6. Days Since First Review (placeholder, no user data)
108
+ days_since_first_review = 0
109
+
110
+ # Select 6 features to match model expectation
111
+ features = [
112
+ review_length, sentiment, punctuation_count,
113
+ avg_word_length, capitalization_ratio, days_since_first_review
114
+ ]
115
+
116
+ return torch.tensor(features, dtype=torch.float32).unsqueeze(0)
117
+
118
+ # Load the custom DistilBERT-ResNet model
119
+ def load_distilbert_model():
120
+ try:
121
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
122
+ model_path = os.path.join(BASE_DIR, "models", "DistilBert_resnet.pth")
123
+ if not os.path.exists(model_path):
124
+ print(f"Model file not found at: {model_path}")
125
+ return None, None
126
+
127
+ # Create the model with matching architecture
128
+ model = ExactDistilBertResNetModel(num_classes=2)
129
+ device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
130
+
131
+ # Load the state dictionary
132
+ state_dict = torch.load(model_path, map_location=device)
133
+ model.load_state_dict(state_dict, strict=True) # Use strict=True to ensure exact match
134
+ model.to(device)
135
+ model.eval()
136
+
137
+ # Load tokenizer
138
+ tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
139
+ print("Custom DistilBERT-ResNet model loaded successfully")
140
+ return model, tokenizer
141
+ except Exception as e:
142
+ print(f"Error loading custom model: {e}")
143
+ return None, None
144
+
145
+ # Generate explanation using Hugging Face Inference API
146
+ def generate_explanation(client, review_text, result_label):
147
+ try:
148
+ prompt = f"Go through the following review and classify it as true or fake review. This review was classified as {result_label}. Explain why it might be classified this way: '{review_text}' Give your answer within only 100 words and avoid headings. Just give one paragraph of explanation. Do not consider the emojis"
149
+
150
+ response = client.chat.completions.create(
151
+ model="mistralai/Mistral-Nemo-Instruct-2407",
152
+ messages=[{"role": "user", "content": prompt}],
153
+ max_tokens=200,
154
+ stream=False
155
+ )
156
+
157
+ explanation = response.choices[0].message.content.strip()
158
+ return explanation
159
+ except Exception as e:
160
+ print(f"Error generating explanation: {e}")
161
+ return f"This review was classified as {result_label}. Due to its content and language patterns, our AI system identified characteristics commonly associated with {result_label.lower()} reviews."
162
+
163
+ # Initialize models
164
+ try:
165
+ print("Starting model loading process...")
166
+ distilbert_model, distilbert_tokenizer = load_distilbert_model()
167
+ if distilbert_model is None or distilbert_tokenizer is None:
168
+ raise Exception("Failed to load DistilBERT model")
169
+
170
+ inference_client = initialize_inference_client()
171
+ if inference_client is None:
172
+ raise Exception("Failed to initialize Hugging Face Inference Client")
173
+
174
+ models_loaded = True
175
+ print("All models and clients loaded successfully!")
176
+ except Exception as e:
177
+ print(f"Error loading models: {e}")
178
+ models_loaded = False
179
+
180
+ @app.route('/analyze', methods=['POST'])
181
+ def analyze():
182
+ if not models_loaded:
183
+ return jsonify({"error": "Models failed to load. Please check server logs."}), 500
184
+
185
+ review_text = request.form.get('review_text', '')
186
+ if not review_text:
187
+ return jsonify({"error": "No review text provided"}), 400
188
+
189
+ # Extract text-based metadata features
190
+ metadata_features = extract_text_features(review_text)
191
+
192
+ image_b64 = None
193
+ if 'review_image' in request.files and request.files['review_image'].filename != '':
194
+ image_file = request.files['review_image']
195
+ try:
196
+ image = Image.open(image_file)
197
+ image.thumbnail((400, 400))
198
+ buffered = io.BytesIO()
199
+ image.save(buffered, format="JPEG")
200
+ image_b64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
201
+ except Exception as e:
202
+ print(f"Error processing image: {e}")
203
+
204
+ try:
205
+ inputs = distilbert_tokenizer(review_text, return_tensors="pt", truncation=True, padding=True, max_length=512)
206
+ device = next(distilbert_model.parameters()).device
207
+ inputs = {k: v.to(device) for k, v in inputs.items()}
208
+
209
+ if metadata_features is not None:
210
+ metadata_features = metadata_features.to(device)
211
+
212
+ with torch.no_grad():
213
+ outputs = distilbert_model(
214
+ input_ids=inputs['input_ids'],
215
+ attention_mask=inputs['attention_mask'],
216
+ metadata=metadata_features
217
+ )
218
+
219
+ prediction = torch.nn.functional.softmax(outputs, dim=1)
220
+ predicted_class = torch.argmax(prediction, dim=1).item()
221
+
222
+ result_label = "Deceptive" if predicted_class == 1 else "True"
223
+
224
+ explanation = generate_explanation(inference_client, review_text, result_label)
225
+
226
+ return jsonify({
227
+ "classification": result_label,
228
+ "explanation": explanation,
229
+ "image": image_b64
230
+ })
231
+
232
+ except Exception as e:
233
+ print(f"Error during classification: {e}")
234
+ return jsonify({"error": f"Classification error: {str(e)}"}), 500
235
+
236
+ @app.route('/')
237
+ def index():
238
+ return render_template('index.html', models_status=models_loaded)
239
+
240
+ if __name__ == '__main__':
241
+ app.run(host='0.0.0.0', port=7860)
models/DistilBert_resnet.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c310d5a30f162cf80ec59e37d6ff0f4d26b4de3a3d55820edb5dfb76562f2f9
3
+ size 310958936
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ flask==3.0.3
2
+ torch==2.6.0
3
+ torchvision==0.21.0
4
+ torchaudio==2.6.0
5
+ transformers==4.48.0
6
+ pillow==11.0.0
7
+ protobuf==5.28.0
8
+ numpy>=1.26.0
9
+ tqdm==4.67.1
10
+ nltk
11
+ huggingface_hub
12
+ --find-links https://download.pytorch.org/whl/cpu/torch_stable.html
static/css/style.css ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --primary-color: #2b6777;
3
+ --secondary-color: #4a5568;
4
+ --accent-color: #38a169;
5
+ --danger-color: #9b2c2c;
6
+ --background-color: #f4f6f8;
7
+ --card-color: #ffffff;
8
+ --text-color: #1a202c;
9
+ --light-text: #6b7280;
10
+ --border-color: #e5e7eb;
11
+ --shadow-color: rgba(0, 0, 0, 0.06);
12
+ }
13
+
14
+ * {
15
+ margin: 0;
16
+ padding: 0;
17
+ box-sizing: border-box;
18
+ }
19
+
20
+ body {
21
+ font-family: 'Roboto', sans-serif;
22
+ background: linear-gradient(135deg, var(--background-color) 0%, #e2e8f0 100%);
23
+ color: var(--text-color);
24
+ line-height: 1.6;
25
+ }
26
+
27
+ .container {
28
+ max-width: 1000px;
29
+ margin: 2rem auto;
30
+ padding: 1.5rem;
31
+ }
32
+
33
+ header {
34
+ background: var(--card-color);
35
+ padding: 2rem;
36
+ border-radius: 16px;
37
+ text-align: center;
38
+ margin-bottom: 2.5rem;
39
+ border: 1px solid var(--border-color);
40
+ }
41
+
42
+ header h1 {
43
+ color: var(--primary-color);
44
+ font-size: 2.75rem;
45
+ font-weight: 700;
46
+ letter-spacing: -0.03em;
47
+ text-transform: uppercase;
48
+ }
49
+
50
+ .tagline {
51
+ color: var(--light-text);
52
+ font-size: 1.15rem;
53
+ font-weight: 300;
54
+ margin-top: 0.75rem;
55
+ font-style: italic;
56
+ }
57
+
58
+ .description {
59
+ background: linear-gradient(45deg, #ffffff, #f8fafc);
60
+ border-radius: 16px;
61
+ padding: 2rem;
62
+ margin-bottom: 2.5rem;
63
+ box-shadow: 0 10px 20px var(--shadow-color);
64
+ text-align: left;
65
+ font-size: 1rem;
66
+ border-right: 4px solid var(--primary-color);
67
+ }
68
+
69
+ .form-container {
70
+ background: var(--card-color);
71
+ border-radius: 16px;
72
+ padding: 2.5rem;
73
+ margin-bottom: 2.5rem;
74
+ box-shadow: 0 10px 20px var(--shadow-color);
75
+ position: relative;
76
+ overflow: hidden;
77
+ }
78
+
79
+ .form-container::before {
80
+ content: '';
81
+ position: absolute;
82
+ top: 0;
83
+ left: 0;
84
+ width: 100%;
85
+ height: 4px;
86
+ background: linear-gradient(to right, var(--primary-color), var(--accent-color));
87
+ }
88
+
89
+ .form-group {
90
+ margin-bottom: 2rem;
91
+ position: relative;
92
+ }
93
+
94
+ label {
95
+ display: inline-block;
96
+ margin-bottom: 0.5rem;
97
+ font-weight: 500;
98
+ color: var(--secondary-color);
99
+ font-size: 0.9rem;
100
+ text-transform: uppercase;
101
+ }
102
+
103
+ textarea {
104
+ width: 100%;
105
+ padding: 1rem 1.25rem;
106
+ border: none;
107
+ border-radius: 10px;
108
+ font-family: 'Roboto', sans-serif;
109
+ font-size: 1rem;
110
+ background: #f9fafb;
111
+ transition: all 0.3s ease;
112
+ box-shadow: inset 0 2px 4px var(--shadow-color);
113
+ }
114
+
115
+ textarea:focus {
116
+ outline: none;
117
+ background: #ffffff;
118
+ box-shadow: 0 0 0 3px rgba(43, 103, 119, 0.15);
119
+ }
120
+
121
+ .file-input-container {
122
+ display: grid;
123
+ gap: 1.5rem;
124
+ }
125
+
126
+ input[type="file"] {
127
+ padding: 0.75rem;
128
+ background: #f9fafb;
129
+ border-radius: 10px;
130
+ border: 1px solid var(--border-color);
131
+ }
132
+
133
+ .file-preview-container {
134
+ margin-top: 1rem;
135
+ }
136
+
137
+ #image-preview {
138
+ max-width: 100%;
139
+ max-height: 220px;
140
+ border-radius: 12px;
141
+ border: 2px solid var(--border-color);
142
+ transition: transform 0.3s ease;
143
+ }
144
+
145
+ #image-preview:hover {
146
+ transform: scale(1.02);
147
+ }
148
+
149
+ button {
150
+ background: linear-gradient(45deg, var(--primary-color), #5187a0);
151
+ color: white;
152
+ border: none;
153
+ padding: 1rem 2.5rem;
154
+ border-radius: 50px;
155
+ font-size: 1rem;
156
+ font-weight: 600;
157
+ cursor: pointer;
158
+ transition: all 0.3s ease;
159
+ display: inline-flex;
160
+ align-items: center;
161
+ gap: 0.5rem;
162
+ }
163
+
164
+ button:hover {
165
+ background: linear-gradient(45deg, var(--secondary-color), #718096);
166
+ transform: translateY(-2px);
167
+ box-shadow: 0 4px 12px var(--shadow-color);
168
+ }
169
+
170
+ .loader {
171
+ display: flex;
172
+ flex-direction: column;
173
+ align-items: center;
174
+ justify-content: center;
175
+ margin: 3rem 0;
176
+ padding: 2rem;
177
+ background: var(--card-color);
178
+ border-radius: 12px;
179
+ }
180
+
181
+ .spinner {
182
+ border: 6px solid var(--border-color);
183
+ border-radius: 50%;
184
+ border-top: 6px solid var(--accent-color);
185
+ width: 48px;
186
+ height: 48px;
187
+ animation: spin 0.9s ease-in-out infinite;
188
+ margin-bottom: 1rem;
189
+ }
190
+
191
+ @keyframes spin {
192
+ 0% { transform: rotate(0deg); }
193
+ 100% { transform: rotate(360deg); }
194
+ }
195
+
196
+ .result-container {
197
+ background: var(--card-color);
198
+ border-radius: 16px;
199
+ margin-bottom: 2.5rem;
200
+ box-shadow: 0 10px 20px var(--shadow-color);
201
+ position: relative;
202
+ border-left: 4px solid var(--accent-color);
203
+ }
204
+
205
+ .result-header {
206
+ background: var(--secondary-color);
207
+ color: white;
208
+ padding: 1.5rem 2.5rem;
209
+ border-radius: 12px 12px 0 0;
210
+ }
211
+
212
+ .result-header h2 {
213
+ font-size: 1.6rem;
214
+ font-weight: 500;
215
+ letter-spacing: 0.05em;
216
+ }
217
+
218
+ .result-body {
219
+ padding: 2.5rem;
220
+ background: linear-gradient(180deg, #ffffff, #f9fafb);
221
+ }
222
+
223
+ .classification-result {
224
+ display: grid;
225
+ grid-template-columns: 1fr auto;
226
+ align-items: center;
227
+ padding: 1.5rem;
228
+ border-radius: 12px;
229
+ background: #f9fafb;
230
+ margin-bottom: 2rem;
231
+ border: 1px solid var(--border-color);
232
+ }
233
+
234
+ .classification-badge {
235
+ padding: 0.75rem 2rem;
236
+ border-radius: 25px;
237
+ font-weight: 700;
238
+ font-size: 1.1rem;
239
+ text-transform: uppercase;
240
+ letter-spacing: 0.05em;
241
+ }
242
+
243
+ .classification-badge.true {
244
+ background: rgba(56, 161, 105, 0.15);
245
+ color: var(--accent-color);
246
+ }
247
+
248
+ .classification-badge.deceptive {
249
+ background: rgba(155, 44, 44, 0.15);
250
+ color: var(--danger-color);
251
+ }
252
+
253
+ .confidence {
254
+ font-size: 1.05rem;
255
+ font-weight: 500;
256
+ color: var(--secondary-color);
257
+ background: #ffffff;
258
+ padding: 0.5rem 1rem;
259
+ border-radius: 8px;
260
+ }
261
+
262
+ .uploaded-image-container {
263
+ margin-bottom: 2.5rem;
264
+ padding: 1.5rem;
265
+ background: #f9fafb;
266
+ border-radius: 12px;
267
+ }
268
+
269
+ .uploaded-image-container h3 {
270
+ margin-bottom: 1.25rem;
271
+ color: var(--primary-color);
272
+ font-weight: 600;
273
+ font-size: 1.15rem;
274
+ text-transform: uppercase;
275
+ }
276
+
277
+ #result-image {
278
+ max-width: 100%;
279
+ border-radius: 12px;
280
+ border: 2px solid var(--border-color);
281
+ transition: all 0.3s ease;
282
+ }
283
+
284
+ #result-image:hover {
285
+ transform: scale(1.02);
286
+ }
287
+
288
+ .explanation-container h3 {
289
+ margin-bottom: 1.25rem;
290
+ color: var(--primary-color);
291
+ font-weight: 600;
292
+ font-size: 1.15rem;
293
+ text-transform: uppercase;
294
+ }
295
+
296
+ .explanation-text {
297
+ background: #ffffff;
298
+ padding: 2rem;
299
+ border-radius: 12px;
300
+ line-height: 1.7;
301
+ font-size: 0.95rem;
302
+ box-shadow: inset 0 2px 4px var(--shadow-color);
303
+ border-left: 4px solid var(--accent-color);
304
+ }
305
+
306
+ footer {
307
+ text-align: center;
308
+ padding: 2.5rem 1rem;
309
+ color: var(--light-text);
310
+ font-size: 0.9rem;
311
+ background: var(--card-color);
312
+ border-radius: 16px;
313
+ margin-top: 2rem;
314
+ border: 1px solid var(--border-color);
315
+ }
316
+
317
+ @media (max-width: 768px) {
318
+ .container {
319
+ padding: 1rem;
320
+ }
321
+
322
+ header h1 {
323
+ font-size: 2rem;
324
+ }
325
+
326
+ .form-container,
327
+ .result-container {
328
+ padding: 1.5rem;
329
+ }
330
+
331
+ .classification-result {
332
+ grid-template-columns: 1fr;
333
+ gap: 1.5rem;
334
+ }
335
+
336
+ button {
337
+ width: 100%;
338
+ padding: 1rem;
339
+ }
340
+
341
+ .description,
342
+ .result-body {
343
+ padding: 1.5rem;
344
+ }
345
+ }
static/js/script.js ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+ const reviewForm = document.getElementById('review-form');
3
+ const reviewTextarea = document.getElementById('review-text');
4
+ const imageInput = document.getElementById('review-image');
5
+ const imagePreview = document.getElementById('image-preview');
6
+ const analyzeBtn = document.getElementById('analyze-btn');
7
+ const loader = document.getElementById('loader');
8
+ const resultContainer = document.getElementById('result-container');
9
+ const classificationBadge = document.getElementById('classification-badge');
10
+ const classificationText = document.getElementById('classification-text');
11
+ // const confidenceValue = document.getElementById('confidence-value');
12
+ const explanationText = document.getElementById('explanation-text');
13
+ const uploadedImageContainer = document.getElementById('uploaded-image-container');
14
+ const resultImage = document.getElementById('result-image');
15
+
16
+ // Handle image preview
17
+ imageInput.addEventListener('change', (e) => {
18
+ const file = e.target.files[0];
19
+ if (file) {
20
+ const reader = new FileReader();
21
+ reader.onload = (event) => {
22
+ imagePreview.src = event.target.result;
23
+ imagePreview.style.display = 'block';
24
+ };
25
+ reader.readAsDataURL(file);
26
+ } else {
27
+ imagePreview.src = '';
28
+ imagePreview.style.display = 'none';
29
+ }
30
+ });
31
+
32
+ // Handle form submission
33
+ reviewForm.addEventListener('submit', async (e) => {
34
+ e.preventDefault();
35
+
36
+ // Basic validation
37
+ if (!reviewTextarea.value.trim()) {
38
+ alert('Please enter a review text to analyze.');
39
+ return;
40
+ }
41
+
42
+ // Show loader, hide results
43
+ loader.style.display = 'flex';
44
+ resultContainer.style.display = 'none';
45
+ analyzeBtn.disabled = true;
46
+
47
+ try {
48
+ // Create form data
49
+ const formData = new FormData();
50
+ formData.append('review_text', reviewTextarea.value.trim());
51
+
52
+ if (imageInput.files.length > 0) {
53
+ formData.append('review_image', imageInput.files[0]);
54
+ }
55
+
56
+ // Send the request
57
+ const response = await fetch('/analyze', {
58
+ method: 'POST',
59
+ body: formData
60
+ });
61
+
62
+ if (!response.ok) {
63
+ const errorData = await response.json();
64
+ throw new Error(errorData.error || 'An error occurred during analysis');
65
+ }
66
+
67
+ const result = await response.json();
68
+
69
+ // Update the UI with the results
70
+ classificationText.textContent = result.classification;
71
+ classificationBadge.className = 'classification-badge';
72
+ classificationBadge.classList.add(result.classification.toLowerCase());
73
+ // confidenceValue.textContent = result.confidence;
74
+ explanationText.textContent = result.explanation;
75
+
76
+ // Handle image display
77
+ if (result.image) {
78
+ resultImage.src = 'data:image/jpeg;base64,' + result.image;
79
+ uploadedImageContainer.style.display = 'block';
80
+ } else {
81
+ uploadedImageContainer.style.display = 'none';
82
+ }
83
+
84
+ // Show results
85
+ resultContainer.style.display = 'block';
86
+
87
+ } catch (error) {
88
+ alert(error.message || 'An error occurred. Please try again.');
89
+ console.error('Error:', error);
90
+ } finally {
91
+ // Hide loader, re-enable button
92
+ loader.style.display = 'none';
93
+ analyzeBtn.disabled = false;
94
+ }
95
+ });
96
+
97
+ // Reset preview when form is reset
98
+ reviewForm.addEventListener('reset', () => {
99
+ imagePreview.src = '';
100
+ imagePreview.style.display = 'none';
101
+ resultContainer.style.display = 'none';
102
+ });
103
+
104
+ // Add a character counter to the textarea
105
+ reviewTextarea.addEventListener('input', function() {
106
+ const maxLength = 500; // You can adjust this
107
+ const currentLength = this.value.length;
108
+
109
+ if (this.nextElementSibling && this.nextElementSibling.classList.contains('char-counter')) {
110
+ this.nextElementSibling.textContent = `${currentLength}/${maxLength} characters`;
111
+ } else {
112
+ const counter = document.createElement('div');
113
+ counter.classList.add('char-counter');
114
+ counter.style.textAlign = 'right';
115
+ counter.style.fontSize = '0.8rem';
116
+ counter.style.color = 'var(--light-text)';
117
+ counter.style.marginTop = '0.25rem';
118
+ counter.textContent = `${currentLength}/${maxLength} characters`;
119
+ this.parentNode.insertBefore(counter, this.nextSibling);
120
+ }
121
+
122
+ if (currentLength > maxLength) {
123
+ this.nextElementSibling.style.color = 'var(--danger-color)';
124
+ } else {
125
+ this.nextElementSibling.style.color = 'var(--light-text)';
126
+ }
127
+ });
128
+
129
+ // Add animations for smooth transitions
130
+ document.querySelectorAll('.form-group, .result-container').forEach(el => {
131
+ el.style.transition = 'all 0.3s ease';
132
+ });
133
+ });
templates/index.html ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Fake Review Detector</title>
7
+ <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
8
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
9
+ <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
10
+ </head>
11
+ <body>
12
+ <div class="container">
13
+ <header>
14
+ <h1>Fake Review Detector</h1>
15
+ <p class="tagline">Powered by DistilBERT + Resnet and Hugging Face Inference</p>
16
+ </header>
17
+
18
+ <section class="description">
19
+ <p>This tool analyzes reviews and determines if they are genuine or deceptive.
20
+ Simply enter your review text below, optionally upload an image, and our AI will analyze it.
21
+ Additionally, Hugging Face inference will explain the classification reasoning.
22
+ </p>
23
+ </section>
24
+
25
+ <div class="form-container">
26
+ <form id="review-form" enctype="multipart/form-data">
27
+ <div class="form-group">
28
+ <label for="review-text">Enter Review Text:</label>
29
+ <textarea id="review-text" name="review_text" rows="5" placeholder="Paste or type the review text here..."></textarea>
30
+ </div>
31
+
32
+ <div class="form-group">
33
+ <label for="review-image">Upload Image (Optional):</label>
34
+ <div class="file-input-container">
35
+ <input type="file" id="review-image" name="review_image" accept="image/*">
36
+ <div class="file-preview-container">
37
+ <img id="image-preview" src="" alt="" style="display: none;">
38
+ </div>
39
+ </div>
40
+ </div>
41
+
42
+ <div class="form-group">
43
+ <button type="submit" id="analyze-btn">Analyze Review</button>
44
+ </div>
45
+ </form>
46
+ </div>
47
+
48
+ <div id="loader" class="loader" style="display: none;">
49
+ <div class="spinner"></div>
50
+ <p>Analyzing...</p>
51
+ </div>
52
+
53
+ <div id="result-container" class="result-container" style="display: none;">
54
+ <div class="result-header">
55
+ <h2>Analysis Result</h2>
56
+ </div>
57
+ <div class="result-body">
58
+ <div class="classification-result">
59
+ <div class="classification-badge" id="classification-badge">
60
+ <span id="classification-text">True</span>
61
+ </div>
62
+ <!-- <div class="confidence">
63
+ <span>Confidence: </span>
64
+ <span id="confidence-value">95%</span>
65
+ </div> -->
66
+ </div>
67
+
68
+ <div class="uploaded-image-container" id="uploaded-image-container" style="display: none;">
69
+ <h3>Uploaded Image:</h3>
70
+ <img id="result-image" src="" alt="Uploaded image">
71
+ </div>
72
+
73
+ <div class="explanation-container">
74
+ <h3>Nemo Model Explanation:</h3>
75
+ <div id="explanation-text" class="explanation-text"></div>
76
+ </div>
77
+ </div>
78
+ </div>
79
+ </div>
80
+
81
+ <script src="{{ url_for('static', filename='js/script.js') }}"></script>
82
+ </body>
83
+ </html>