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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import joblib
|
| 5 |
+
import sqlite3
|
| 6 |
+
import re
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
from transformers import pipeline
|
| 9 |
+
from better_profanity import profanity
|
| 10 |
+
|
| 11 |
+
# ---------------------- Shared DB Setup ----------------------
|
| 12 |
+
profanity.load_censor_words()
|
| 13 |
+
db = sqlite3.connect("anomaly1.db", check_same_thread=False)
|
| 14 |
+
cursor = db.cursor()
|
| 15 |
+
|
| 16 |
+
# ---------------------- Load Models ----------------------
|
| 17 |
+
# Bid anomaly models
|
| 18 |
+
bid_model = joblib.load("anomaly_model.pkl")
|
| 19 |
+
label_encoder = joblib.load("label_encoder.pkl")
|
| 20 |
+
df = pd.read_csv("cleaned_dataset.csv")[['Product Name', 'Price']].dropna()
|
| 21 |
+
|
| 22 |
+
# Review anomaly models
|
| 23 |
+
spam_model = joblib.load("spam_classifier.pkl")
|
| 24 |
+
toxicity_model = pipeline("text-classification", model="unitary/toxic-bert")
|
| 25 |
+
|
| 26 |
+
# ---------------------- BID ANOMALY FUNCTION ----------------------
|
| 27 |
+
def connect_to_db():
|
| 28 |
+
return sqlite3.connect("sql.db")
|
| 29 |
+
|
| 30 |
+
def detect_and_act(product_name, bid_price):
|
| 31 |
+
vendor_id = 1 # Static for now
|
| 32 |
+
try:
|
| 33 |
+
conn = connect_to_db()
|
| 34 |
+
cursor = conn.cursor()
|
| 35 |
+
|
| 36 |
+
bid_price = float(bid_price)
|
| 37 |
+
encoded_product = label_encoder.transform([product_name])[0]
|
| 38 |
+
input_data = np.array([[encoded_product, bid_price]])
|
| 39 |
+
prediction = bid_model.predict(input_data)
|
| 40 |
+
|
| 41 |
+
product_data = df[df['Product Name'] == product_name]
|
| 42 |
+
mean_price = product_data['Price'].mean()
|
| 43 |
+
std_price = product_data['Price'].std()
|
| 44 |
+
min_range = mean_price - 2 * std_price
|
| 45 |
+
max_range = mean_price + 2 * std_price
|
| 46 |
+
bid_valid = min_range <= bid_price <= max_range
|
| 47 |
+
|
| 48 |
+
cursor.execute("SELECT * FROM vendors WHERE vendor_id = ?", (vendor_id,))
|
| 49 |
+
vendor = cursor.fetchone()
|
| 50 |
+
if not vendor:
|
| 51 |
+
return "β οΈ Vendor not found!"
|
| 52 |
+
|
| 53 |
+
cursor.execute("SELECT bid_id FROM bids WHERE vendor_id = ? ORDER BY bid_id DESC LIMIT 1", (vendor_id,))
|
| 54 |
+
bid = cursor.fetchone()
|
| 55 |
+
if not bid:
|
| 56 |
+
return "β οΈ No bid found in the system to associate with a vendor."
|
| 57 |
+
|
| 58 |
+
bid_id = bid[0]
|
| 59 |
+
|
| 60 |
+
if prediction[0] == -1 and not bid_valid:
|
| 61 |
+
cursor.execute("UPDATE vendors SET anomaly_count = anomaly_count + 1 WHERE vendor_id = ?", (vendor_id,))
|
| 62 |
+
conn.commit()
|
| 63 |
+
|
| 64 |
+
cursor.execute("SELECT anomaly_count FROM vendors WHERE vendor_id = ?", (vendor_id,))
|
| 65 |
+
anomaly_count = cursor.fetchone()[0]
|
| 66 |
+
|
| 67 |
+
if anomaly_count >= 3:
|
| 68 |
+
cursor.execute("UPDATE vendors SET blocked_status = 1 WHERE vendor_id = ?", (vendor_id,))
|
| 69 |
+
conn.commit()
|
| 70 |
+
return "β Vendor permanently blocked after 3 fake bids."
|
| 71 |
+
|
| 72 |
+
elif anomaly_count == 2:
|
| 73 |
+
block_until = datetime.now() + timedelta(hours=24)
|
| 74 |
+
cursor.execute("UPDATE vendors SET suspended_until = ? WHERE vendor_id = ?",
|
| 75 |
+
(block_until.strftime("%Y-%m-%d %H:%M:%S"), vendor_id))
|
| 76 |
+
conn.commit()
|
| 77 |
+
return "β οΈ Vendor temporarily blocked for 24 hours (2nd fake bid)."
|
| 78 |
+
|
| 79 |
+
else:
|
| 80 |
+
return "β οΈ Fake bid detected. Warning issued."
|
| 81 |
+
|
| 82 |
+
elif prediction[0] == -1 or not bid_valid:
|
| 83 |
+
block_until = datetime.now() + timedelta(hours=24)
|
| 84 |
+
cursor.execute("UPDATE vendors SET suspended_until = ? WHERE vendor_id = ?",
|
| 85 |
+
(block_until.strftime("%Y-%m-%d %H:%M:%S"), vendor_id))
|
| 86 |
+
conn.commit()
|
| 87 |
+
return "β οΈ Bid suspicious. Vendor temporarily blocked for 24 hours."
|
| 88 |
+
|
| 89 |
+
else:
|
| 90 |
+
return "β
Bid is normal."
|
| 91 |
+
|
| 92 |
+
except Exception as e:
|
| 93 |
+
return f"β Error: {str(e)}"
|
| 94 |
+
finally:
|
| 95 |
+
conn.close()
|
| 96 |
+
|
| 97 |
+
# ---------------------- REVIEW ANOMALY FUNCTIONS ----------------------
|
| 98 |
+
|
| 99 |
+
def is_toxic(text):
|
| 100 |
+
try:
|
| 101 |
+
result = toxicity_model(text)[0]
|
| 102 |
+
return result['label'].lower() == "toxic" and result['score'] > 0.7
|
| 103 |
+
except:
|
| 104 |
+
return False
|
| 105 |
+
|
| 106 |
+
def is_low_quality(text):
|
| 107 |
+
return len(text.strip()) < 10 or text.strip().isupper() or re.search(r"(.)\1{3,}", text)
|
| 108 |
+
|
| 109 |
+
def contains_suspicious_content(text):
|
| 110 |
+
patterns = [r"\b\d{10}\b", r"\bcall me\b", r"\bwhatsapp\b", r"\bnumber\b", r"\bcontact\b", r"\bemail\b"]
|
| 111 |
+
return any(re.search(p, text.lower()) for p in patterns)
|
| 112 |
+
|
| 113 |
+
def is_nonsensical_structure(text):
|
| 114 |
+
patterns = [r"\bi am a\b", r"\bi will be a\b", r"\bthis is my\b"]
|
| 115 |
+
return any(re.search(p, text.lower()) for p in patterns)
|
| 116 |
+
|
| 117 |
+
def basic_anomaly_score(text):
|
| 118 |
+
score = 0
|
| 119 |
+
if is_low_quality(text): score += 0.3
|
| 120 |
+
if contains_suspicious_content(text): score += 0.3
|
| 121 |
+
if is_nonsensical_structure(text): score += 0.2
|
| 122 |
+
if len(text.split()) < 3: score += 0.2
|
| 123 |
+
return score
|
| 124 |
+
|
| 125 |
+
def predict_review(text):
|
| 126 |
+
text = text.strip()
|
| 127 |
+
if not text:
|
| 128 |
+
return "β οΈ Please enter a review."
|
| 129 |
+
|
| 130 |
+
flags = []
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
if spam_model.predict([text])[0]:
|
| 134 |
+
flags.append("Spam")
|
| 135 |
+
except:
|
| 136 |
+
flags.append("Spam Detection Failed")
|
| 137 |
+
|
| 138 |
+
if is_toxic(text): flags.append("Toxic")
|
| 139 |
+
if is_low_quality(text): flags.append("Low Quality")
|
| 140 |
+
if contains_suspicious_content(text): flags.append("Suspicious")
|
| 141 |
+
if is_nonsensical_structure(text): flags.append("Nonsensical")
|
| 142 |
+
if len(text.split()) < 3: flags.append("Too Short")
|
| 143 |
+
|
| 144 |
+
score = basic_anomaly_score(text)
|
| 145 |
+
if score >= 0.5:
|
| 146 |
+
flags.append("Anomalous")
|
| 147 |
+
|
| 148 |
+
prediction = ", ".join(flags) if flags else "Normal"
|
| 149 |
+
now = datetime.now()
|
| 150 |
+
is_anomaly = 1 if "Anomalous" in flags else 0
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
cursor.execute("SELECT user_id FROM users ORDER BY user_id DESC LIMIT 1")
|
| 154 |
+
result = cursor.fetchone()
|
| 155 |
+
user_id = result[0] if result else 1
|
| 156 |
+
vendor_id = 1
|
| 157 |
+
|
| 158 |
+
cursor.execute("""
|
| 159 |
+
INSERT INTO reviews (user_id, vendor_id, review_text, timestamp, is_anomaly, prediction, review)
|
| 160 |
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
| 161 |
+
""", (user_id, vendor_id, text, now, is_anomaly, prediction, text))
|
| 162 |
+
db.commit()
|
| 163 |
+
|
| 164 |
+
if is_anomaly:
|
| 165 |
+
suspend_until = now + timedelta(hours=24)
|
| 166 |
+
cursor.execute("UPDATE users SET suspended_until = ? WHERE user_id = ?", (suspend_until, user_id))
|
| 167 |
+
db.commit()
|
| 168 |
+
return f"β {prediction}\nUser temporarily suspended until {suspend_until.strftime('%Y-%m-%d %H:%M:%S')}."
|
| 169 |
+
|
| 170 |
+
return f"β
Prediction: {prediction}"
|
| 171 |
+
|
| 172 |
+
except Exception as e:
|
| 173 |
+
return f"β οΈ Database Error: {str(e)}"
|
| 174 |
+
|
| 175 |
+
# ---------------------- Gradio UI ----------------------
|
| 176 |
+
|
| 177 |
+
bid_interface = gr.Interface(
|
| 178 |
+
fn=detect_and_act,
|
| 179 |
+
inputs=["text", "text"],
|
| 180 |
+
outputs="text",
|
| 181 |
+
title="π‘οΈ BID ANOMALY",
|
| 182 |
+
description="Enter Product Name and Bid Price"
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
review_interface = gr.Interface(
|
| 186 |
+
fn=predict_review,
|
| 187 |
+
inputs=gr.Textbox(lines=4, placeholder="Type a product review here...", label="Review Text"),
|
| 188 |
+
outputs=gr.Textbox(label="Prediction"),
|
| 189 |
+
title="ποΈ REVIEW ANOMALY",
|
| 190 |
+
description="Enter a review to check for spam, toxicity, or fake content"
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# ---------------------- Launch Tabbed Interface ----------------------
|
| 194 |
+
|
| 195 |
+
gr.TabbedInterface(
|
| 196 |
+
interface_list=[review_interface, bid_interface],
|
| 197 |
+
tab_names=["REVIEW ANOMALY", "BID ANOMALY"]
|
| 198 |
+
)
|
| 199 |
+
.launch()
|