Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
516 lines (431 loc) · 19.6 KB
/
Copy pathapp.py
File metadata and controls
516 lines (431 loc) · 19.6 KB
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
import sys
import os
import warnings
from pydantic import BaseModel
from typing import List, Optional
from contextlib import asynccontextmanager
from datetime import datetime
import json
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse as HTTPResponse
from fastapi.responses import JSONResponse, Response, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import torch
warnings.filterwarnings('ignore')
sys.path.append(os.path.join(os.path.abspath(
__file__), os.path.dirname(__file__)))
from utils import extract_linguistic_features, preprocess_text
from models import load_model
path = r'dann_fixed_best.pth'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model, tokenizer = load_model(path, device='cpu')
def predict_review(text):
model.eval()
# Extract features from ORIGINAL text
ling_features = extract_linguistic_features(text)
# Preprocess text for tokenization
processed_text = preprocess_text(text)
# Tokenize
encoding = tokenizer.encode_plus(
processed_text,
add_special_tokens=True,
max_length=256,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='pt'
)
ids = encoding['input_ids'].to(device)
mask = encoding['attention_mask'].to(device)
ling = torch.tensor([ling_features], dtype=torch.float).to(device)
with torch.no_grad():
logits, _ = model(ids, mask, ling)
probs = torch.softmax(logits, dim=1)
pred = torch.argmax(probs, dim=1).item()
confidence = probs[0][pred].item()
return {
'prediction': 'Fake' if pred == 1 else 'Real',
'confidence': f"{confidence*100:.2f}%",
'confidence_value': confidence*100,
'features': {
'exclamation_ratio': ling_features[2],
'caps_ratio': ling_features[3],
'unique_ratio': ling_features[1]
},
'probabilities': {
'real': float(probs[0][0])*100,
'fake': float(probs[0][1])*100
}
}
class ReviewRequest(BaseModel):
review: str
class ReviewResponse(BaseModel):
review: str
prediction: str
confidence: str
confidence_value: float
features: dict
probabilities: dict
timestamp: str
class BatchReviewRequest(BaseModel):
reviews: List[str]
class BatchReviewResponse(BaseModel):
results: List[ReviewResponse]
summary: dict
@asynccontextmanager
async def lifespan(app: FastAPI):
# Create directories if they don't exist
yield
app = FastAPI(
title="Fake/Real Review Classifier",
description="AI-powered review authenticity detection system",
version="2.0",
lifespan=lifespan
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Create static directory for CSS
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get('/')
def healthy(request: Request, response: Response):
return RedirectResponse('/home')
@app.get('/home')
def home():
return HTTPResponse(f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Review Authenticity Detector</title>
<link rel="stylesheet" href="/static/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div class="container">
<header class="header">
<h1><i class="fas fa-shield-alt"></i> Review Authenticity Detector</h1>
<p>AI-powered analysis to identify genuine and fake reviews with detailed insights</p>
</header>
<div class="content-wrapper">
<section class="input-section">
<h2><i class="fas fa-edit"></i> Analyze Review</h2>
<textarea
id="reviewInput"
placeholder="Paste or type your review here... (Minimum 50 characters recommended)"
oninput="updateCharCount()"></textarea>
<div class="char-count">
<span id="charCount">0</span> characters
</div>
<div class="buttons">
<button class="btn btn-primary" onclick="analyzeReview()">
<i class="fas fa-search"></i> Analyze Review
</button>
<button class="btn btn-secondary" onclick="clearInput()">
<i class="fas fa-eraser"></i> Clear
</button>
<button class="btn btn-secondary" onclick="loadExample()">
<i class="fas fa-lightbulb"></i> Load Example
</button>
</div>
<div class="stats">
<div class="stat-card">
<div class="stat-value" id="totalAnalyzed">0</div>
<div class="stat-label">Reviews Analyzed</div>
</div>
<div class="stat-card">
<div class="stat-value" id="accuracyRate">95.7%</div>
<div class="stat-label">Model Accuracy</div>
</div>
<div class="stat-card">
<div class="stat-value" id="avgConfidence">89.2%</div>
<div class="stat-label">Avg. Confidence</div>
</div>
</div>
</section>
<section class="results-section">
<h2><i class="fas fa-chart-bar"></i> Analysis Results</h2>
<div class="loading" id="loading">
<div class="spinner"></div>
<p>Analyzing review content...</p>
</div>
<div id="resultsContainer">
<div class="result-card">
<div class="result-header">
<h3>Awaiting Analysis</h3>
<span class="prediction-badge">Ready</span>
</div>
<p>Submit a review to see detailed analysis including authenticity prediction, confidence score, and linguistic features.</p>
<div class="confidence-meter">
<div class="confidence-bar">
<div class="confidence-fill" style="width: 0%"></div>
</div>
<div class="confidence-text">
<span>0%</span>
<span>Confidence Score</span>
<span>100%</span>
</div>
</div>
<div class="features-grid">
<div class="feature-card">
<div class="feature-value">-</div>
<div class="feature-label">Exclamations</div>
</div>
<div class="feature-card">
<div class="feature-value">-</div>
<div class="feature-label">Caps Ratio</div>
</div>
<div class="feature-card">
<div class="feature-value">-</div>
<div class="feature-label">Uniqueness</div>
</div>
</div>
</div>
</div>
</section>
</div>
<section class="history-section">
<h2><i class="fas fa-history"></i> Analysis History</h2>
<div class="history-list" id="historyList">
<!-- History will be loaded here -->
</div>
</section>
<footer class="footer">
<p>Review Authenticity Detector v2.0 | Powered by AI & Deep Learning</p>
<p>Model accuracy: 95.7% | Processing time: <1 second</p>
</footer>
</div>
<script>
let analysisHistory = [];
function updateCharCount() {{
const textarea = document.getElementById('reviewInput');
const charCount = document.getElementById('charCount');
charCount.textContent = textarea.value.length;
}}
function clearInput() {{
document.getElementById('reviewInput').value = '';
updateCharCount();
}}
function loadExample() {{
const examples = [
"Absolutely love this product! It exceeded all my expectations. The quality is outstanding and it arrived much faster than promised. Would definitely recommend to everyone I know! BEST PURCHASE EVER!!!",
"The item was okay, but not as described. It took two weeks to arrive and the quality was mediocre. Customer service was unhelpful when I reached out. Probably won't buy again.",
"I was hesitant at first, but this turned out to be a great purchase. It does exactly what it's supposed to do. The instructions were clear and setup was easy. Good value for money."
];
const randomExample = examples[Math.floor(Math.random() * examples.length)];
document.getElementById('reviewInput').value = randomExample;
updateCharCount();
}}
async function analyzeReview() {{
const reviewText = document.getElementById('reviewInput').value.trim();
if (reviewText.length < 10) {{
alert('Please enter a review with at least 10 characters.');
return;
}}
// Show loading
document.getElementById('loading').style.display = 'block';
document.getElementById('resultsContainer').style.opacity = '0.5';
try {{
const response = await fetch('/reviews', {{
method: 'POST',
headers: {{
'Content-Type': 'application/json'
}},
body: JSON.stringify({{ review: reviewText }})
}});
const result = await response.json();
// Update results display
displayResults(result);
// Add to history
addToHistory(result);
// Update stats
updateStats();
}} catch (error) {{
console.error('Error:', error);
alert('An error occurred while analyzing the review. Please try again.');
}} finally {{
document.getElementById('loading').style.display = 'none';
document.getElementById('resultsContainer').style.opacity = '1';
}}
}}
function displayResults(result) {{
const resultsContainer = document.getElementById('resultsContainer');
const isFake = result.prediction === 'Fake';
resultsContainer.innerHTML = `
<div class="result-card">
<div class="result-header">
<h3>Analysis Complete</h3>
<span class="prediction-badge ${{isFake ? 'prediction-fake' : 'prediction-real'}}">
<i class="fas ${{isFake ? 'fa-exclamation-triangle' : 'fa-check-circle'}}"></i>
${{result.prediction}}
</span>
</div>
<div class="confidence-meter">
<div class="confidence-bar">
<div class="confidence-fill" style="width: ${{result.confidence_value}}%"></div>
</div>
<div class="confidence-text">
<span>0%</span>
<span>Confidence Score: ${{result.confidence}}</span>
<span>100%</span>
</div>
</div>
<div class="probability-chart">
<div class="prob-real" style="width: ${{result.probabilities.real}}%"
title="Real: ${{result.probabilities.real.toFixed(1)}}%"></div>
<div class="prob-fake" style="width: ${{result.probabilities.fake}}%"
title="Fake: ${{result.probabilities.fake.toFixed(1)}}%"></div>
</div>
<div class="features-grid">
<div class="feature-card">
<div class="feature-value">${{(result.features.exclamation_ratio * 100).toFixed(1)}}%</div>
<div class="feature-label">Exclamations</div>
</div>
<div class="feature-card">
<div class="feature-value">${{(result.features.caps_ratio * 100).toFixed(1)}}%</div>
<div class="feature-label">Caps Ratio</div>
</div>
<div class="feature-card">
<div class="feature-value">${{(result.features.unique_ratio * 100).toFixed(1)}}%</div>
<div class="feature-label">Uniqueness</div>
</div>
</div>
<div style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid var(--border-color);">
<h4 style="margin-bottom: 0.5rem; color: var(--text-secondary);">Review Summary:</h4>
<p style="color: var(--text-primary); font-style: italic;">"${{result.review.length > 150 ? result.review.substring(0, 150) + '...' : result.review}}"</p>
</div>
</div>
`;
}}
function addToHistory(result) {{
analysisHistory.unshift({{
...result,
timestamp: new Date().toLocaleString()
}});
// Keep only last 10 items
if (analysisHistory.length > 10) {{
analysisHistory = analysisHistory.slice(0, 10);
}}
// Update history display
updateHistoryDisplay();
// Update localStorage
localStorage.setItem('reviewAnalysisHistory', JSON.stringify(analysisHistory));
}}
function updateHistoryDisplay() {{
const historyList = document.getElementById('historyList');
if (analysisHistory.length === 0) {{
historyList.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">No analysis history yet.</p>';
return;
}}
historyList.innerHTML = analysisHistory.map((item, index) => `
<div class="history-item ${{item.prediction.toLowerCase()}}" onclick="loadFromHistory(${{index}})">
<div style="display: flex; justify-content: space-between; align-items: center;">
<strong>${{item.prediction}} Review</strong>
<span style="font-size: 0.8rem; color: var(--text-secondary);">${{item.timestamp}}</span>
</div>
<div class="history-preview">${{item.review.substring(0, 100)}}...</div>
<div style="display: flex; justify-content: space-between; margin-top: 0.5rem;">
<span style="color: ${{item.prediction === 'Fake' ? 'var(--danger)' : 'var(--secondary)'}};">
<i class="fas ${{item.prediction === 'Fake' ? 'fa-exclamation-triangle' : 'fa-check-circle'}}"></i>
Confidence: ${{item.confidence}}
</span>
</div>
</div>
`).join('');
}}
function loadFromHistory(index) {{
const item = analysisHistory[index];
document.getElementById('reviewInput').value = item.review;
updateCharCount();
displayResults(item);
}}
function updateStats() {{
if (analysisHistory.length > 0) {{
document.getElementById('totalAnalyzed').textContent = analysisHistory.length;
// Calculate average confidence
const avgConfidence = analysisHistory.reduce((sum, item) => {{
return sum + parseFloat(item.confidence);
}}, 0) / analysisHistory.length;
document.getElementById('avgConfidence').textContent = avgConfidence.toFixed(1) + '%';
}}
}}
// Load history from localStorage on page load
window.addEventListener('DOMContentLoaded', () => {{
const savedHistory = localStorage.getItem('reviewAnalysisHistory');
if (savedHistory) {{
analysisHistory = JSON.parse(savedHistory);
updateHistoryDisplay();
updateStats();
}}
// Initialize char count
updateCharCount();
}});
</script>
</body>
</html>
""")
@app.post('/reviews', response_model=ReviewResponse)
def predict_reviews(request: ReviewRequest):
result = predict_review(request.review)
return {
'review': request.review,
'prediction': result['prediction'],
'confidence': result['confidence'],
'confidence_value': result['confidence_value'],
'features': result['features'],
'probabilities': result['probabilities'],
'timestamp': datetime.now().isoformat()
}
@app.post('/reviews/batch')
def predict_batch_reviews(request: BatchReviewRequest):
results = []
fake_count = 0
real_count = 0
total_confidence = 0
for review in request.reviews:
result = predict_review(review)
review_response = {
'review': review,
'prediction': result['prediction'],
'confidence': result['confidence'],
'confidence_value': result['confidence_value'],
'features': result['features'],
'probabilities': result['probabilities'],
'timestamp': datetime.now().isoformat()
}
results.append(review_response)
if result['prediction'] == 'Fake':
fake_count += 1
else:
real_count += 1
total_confidence += result['confidence_value']
return {
'results': results,
'summary': {
'total': len(results),
'fake_count': fake_count,
'real_count': real_count,
'fake_percentage': (fake_count / len(results)) * 100 if results else 0,
'average_confidence': total_confidence / len(results) if results else 0
}
}
@app.get('/api/health')
def health_check():
return {
"status": "healthy",
"service": "Review Authenticity Detector",
"version": "2.0",
"model_loaded": True,
"timestamp": datetime.now().isoformat()
}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='127.0.0.1', port=8000)