DataWhiz07 commited on
Commit
ce9dba0
Β·
verified Β·
1 Parent(s): 3e8edf5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -37
app.py CHANGED
@@ -1,38 +1,199 @@
1
  import gradio as gr
2
- from review_app import predict_review
3
- from bidding_app import detect_and_act
4
-
5
- # ------------- Main Combined Function -------------
6
- def analyze_all(review_text, product_name, bid_price):
7
- review_result = predict_review(review_text)
8
- bid_result = detect_and_act(product_name, bid_price)
9
-
10
- return {
11
- "Review Analysis": review_result,
12
- "Bidding Analysis": bid_result
13
- }
14
-
15
- # ------------- Gradio Interface Setup -------------
16
- with gr.Blocks(title="TrustCheck: Anomaly Detection in Reviews & Bidding") as demo:
17
- gr.Markdown("# πŸ›‘οΈ TrustCheck")
18
- gr.Markdown("Analyze vendor reviews and bids for anomalies like spam, toxicity, and fake pricing.")
19
-
20
- with gr.Row():
21
- with gr.Column():
22
- review_input = gr.Textbox(label="πŸ“ Review Text", placeholder="Enter a vendor or product review")
23
- product_input = gr.Textbox(label="πŸ“¦ Product Name", placeholder="Enter product name used in bidding")
24
- bid_input = gr.Textbox(label="πŸ’° Bid Price", placeholder="Enter bidding price")
25
- submit_btn = gr.Button("πŸ” Analyze")
26
-
27
- with gr.Column():
28
- review_output = gr.Textbox(label="πŸ“Š Review Analysis")
29
- bid_output = gr.Textbox(label="πŸ“Š Bidding Analysis")
30
-
31
- submit_btn.click(
32
- fn=analyze_all,
33
- inputs=[review_input, product_input, bid_input],
34
- outputs=[review_output, bid_output]
35
- )
36
-
37
- # ------------- Launch Interface -------------
38
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()