Spaces:
Sleeping
Sleeping
Adding code for app.py and updating requirements.txt
Browse files- app.py +214 -1
- requirements.txt +7 -1
app.py
CHANGED
@@ -1,4 +1,217 @@
|
|
1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
|
4 |
-
st.write("#Validate URL Application ")
|
|
|
1 |
import streamlit as st
|
2 |
+
import os
|
3 |
+
import requests
|
4 |
+
from bs4 import BeautifulSoup
|
5 |
+
from sentence_transformers import SentenceTransformer, util
|
6 |
+
from transformers import pipeline
|
7 |
+
|
8 |
+
class URLValidator:
|
9 |
+
"""
|
10 |
+
A production-ready URL validation class that evaluates the credibility of a webpage
|
11 |
+
using multiple factors: domain trust, content relevance, fact-checking, bias detection, citations, and security.
|
12 |
+
"""
|
13 |
+
|
14 |
+
def __init__(self):
|
15 |
+
# API Keys
|
16 |
+
self.serpapi_key = os.genenv('SERPAPI_KEY')
|
17 |
+
self.google_safe_browsing_key = os.getenv('GOOGLE_SAFE_KEY')
|
18 |
+
|
19 |
+
# Load models once to avoid redundant API calls
|
20 |
+
self.similarity_model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')
|
21 |
+
self.fake_news_classifier = pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection")
|
22 |
+
self.sentiment_analyzer = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment")
|
23 |
+
|
24 |
+
def fetch_page_content(self, url: str) -> str:
|
25 |
+
""" Fetches and extracts text content from the given URL. """
|
26 |
+
try:
|
27 |
+
response = requests.get(url, timeout=10)
|
28 |
+
response.raise_for_status()
|
29 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
30 |
+
return " ".join([p.text for p in soup.find_all("p")]) # Extract paragraph text
|
31 |
+
except requests.RequestException:
|
32 |
+
return "" # Fail gracefully by returning an empty string
|
33 |
+
|
34 |
+
def get_domain_trust(self, url: str, content: str) -> int:
|
35 |
+
""" Computes the domain trust score based on available data sources. """
|
36 |
+
trust_scores = []
|
37 |
+
|
38 |
+
# Hugging Face Fake News Detector
|
39 |
+
if content:
|
40 |
+
try:
|
41 |
+
trust_scores.append(self.get_domain_trust_huggingface(content))
|
42 |
+
except:
|
43 |
+
pass
|
44 |
+
|
45 |
+
# Compute final score (average of available scores)
|
46 |
+
return int(sum(trust_scores) / len(trust_scores)) if trust_scores else 50
|
47 |
+
|
48 |
+
def get_domain_trust_huggingface(self, content: str) -> int:
|
49 |
+
""" Uses a Hugging Face fake news detection model to assess credibility. """
|
50 |
+
if not content:
|
51 |
+
return 50 # Default score if no content available
|
52 |
+
result = self.fake_news_classifier(content[:512])[0] # Process only first 512 characters
|
53 |
+
return 100 if result["label"] == "REAL" else 30 if result["label"] == "FAKE" else 50
|
54 |
+
|
55 |
+
def compute_similarity_score(self, user_query: str, content: str) -> int:
|
56 |
+
""" Computes semantic similarity between user query and page content. """
|
57 |
+
if not content:
|
58 |
+
return 0
|
59 |
+
return int(util.pytorch_cos_sim(self.similarity_model.encode(user_query), self.similarity_model.encode(content)).item() * 100)
|
60 |
+
|
61 |
+
def check_facts(self, content: str) -> int:
|
62 |
+
""" Cross-checks extracted content with Google Fact Check API. """
|
63 |
+
if not content:
|
64 |
+
return 50
|
65 |
+
api_url = f"https://toolbox.google.com/factcheck/api/v1/claimsearch?query={content[:200]}"
|
66 |
+
try:
|
67 |
+
response = requests.get(api_url)
|
68 |
+
data = response.json()
|
69 |
+
return 80 if "claims" in data and data["claims"] else 40
|
70 |
+
except:
|
71 |
+
return 50 # Default uncertainty score
|
72 |
+
|
73 |
+
def check_google_scholar(self, url: str) -> int:
|
74 |
+
""" Checks Google Scholar citations using SerpAPI. """
|
75 |
+
serpapi_key = self.serpapi_key
|
76 |
+
params = {"q": url, "engine": "google_scholar", "api_key": serpapi_key}
|
77 |
+
try:
|
78 |
+
response = requests.get("https://serpapi.com/search", params=params)
|
79 |
+
data = response.json()
|
80 |
+
return min(len(data.get("organic_results", [])) * 10, 100) # Normalize
|
81 |
+
except:
|
82 |
+
return 0 # Default to no citations
|
83 |
+
|
84 |
+
def detect_bias(self, content: str) -> int:
|
85 |
+
""" Uses NLP sentiment analysis to detect potential bias in content. """
|
86 |
+
if not content:
|
87 |
+
return 50
|
88 |
+
sentiment_result = self.sentiment_analyzer(content[:512])[0]
|
89 |
+
return 100 if sentiment_result["label"] == "POSITIVE" else 50 if sentiment_result["label"] == "NEUTRAL" else 30
|
90 |
+
|
91 |
+
def get_star_rating(self, score: float) -> tuple:
|
92 |
+
""" Converts a score (0-100) into a 1-5 star rating. """
|
93 |
+
stars = max(1, min(5, round(score / 20))) # Normalize 100-scale to 5-star scale
|
94 |
+
return stars, "⭐" * stars
|
95 |
+
|
96 |
+
def generate_explanation(self, domain_trust, similarity_score, fact_check_score, bias_score, citation_score, safe_browsing_score, final_score) -> str:
|
97 |
+
""" Generates a human-readable explanation for the score. """
|
98 |
+
reasons = []
|
99 |
+
if domain_trust < 50:
|
100 |
+
reasons.append("The source has low domain authority.")
|
101 |
+
else:
|
102 |
+
reasons.append("The source has high domain authority.")
|
103 |
+
if similarity_score < 50:
|
104 |
+
reasons.append("The content is not highly relevant to your query.")
|
105 |
+
else:
|
106 |
+
reasons.append("The content is highly relevant to your query.")
|
107 |
+
if fact_check_score < 50:
|
108 |
+
reasons.append("Limited fact-checking verification found.")
|
109 |
+
else:
|
110 |
+
reasons.append("High level of fact-checking verification found.")
|
111 |
+
if bias_score < 50:
|
112 |
+
reasons.append("Potential bias detected in the content.")
|
113 |
+
else:
|
114 |
+
reasons.append("No bias detected in the content.")
|
115 |
+
if citation_score < 30:
|
116 |
+
reasons.append("Few citations found for this content.")
|
117 |
+
else:
|
118 |
+
reasons.append("High level of citations found for this content.")
|
119 |
+
if safe_browsing_score < 50:
|
120 |
+
reasons.append("No malicious content detected.")
|
121 |
+
else:
|
122 |
+
reasons.append("Possible malicious content detected.")
|
123 |
+
|
124 |
+
return " ".join(reasons) if reasons else "This source is highly credible and relevant."
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
def check_google_safe_browsing(self, url: str) -> int:
|
129 |
+
"""
|
130 |
+
Uses Google Safe Browsing API to check if a URL is malicious.
|
131 |
+
Returns:
|
132 |
+
- 100 if safe
|
133 |
+
- 30 if flagged as potentially harmful
|
134 |
+
- 10 if confirmed malicious
|
135 |
+
"""
|
136 |
+
api_url = f"https://safebrowsing.googleapis.com/v4/threatMatches:find?key={self.google_safe_browsing_key}"
|
137 |
+
payload = {
|
138 |
+
"client": {
|
139 |
+
"clientId": "your-app",
|
140 |
+
"clientVersion": "1.0"
|
141 |
+
},
|
142 |
+
"threatInfo": {
|
143 |
+
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"],
|
144 |
+
"platformTypes": ["ANY_PLATFORM"],
|
145 |
+
"threatEntryTypes": ["URL"],
|
146 |
+
"threatEntries": [{"url": url}]
|
147 |
+
}
|
148 |
+
}
|
149 |
+
|
150 |
+
try:
|
151 |
+
response = requests.post(api_url, json=payload)
|
152 |
+
data = response.json()
|
153 |
+
if "matches" in data:
|
154 |
+
return 10 # Malicious URL detected
|
155 |
+
return 100 # Safe URL
|
156 |
+
except:
|
157 |
+
return 50 # Default score if API request fails
|
158 |
+
|
159 |
+
def rate_url_validity(self, user_query: str, url: str) -> dict:
|
160 |
+
""" Main function to evaluate the validity of a webpage. """
|
161 |
+
content = self.fetch_page_content(url)
|
162 |
+
|
163 |
+
domain_trust = self.get_domain_trust(url, content)
|
164 |
+
similarity_score = self.compute_similarity_score(user_query, content)
|
165 |
+
fact_check_score = self.check_facts(content)
|
166 |
+
bias_score = self.detect_bias(content)
|
167 |
+
citation_score = self.check_google_scholar(url)
|
168 |
+
safe_browsing_score = self.check_google_safe_browsing(url)
|
169 |
+
|
170 |
+
final_score = (
|
171 |
+
(0.30 * domain_trust) +
|
172 |
+
(0.30 * similarity_score) +
|
173 |
+
(0.20 * fact_check_score) +
|
174 |
+
(0.10 * bias_score) +
|
175 |
+
(0.10 * citation_score) +
|
176 |
+
(0.05 * safe_browsing_score)
|
177 |
+
)
|
178 |
+
|
179 |
+
stars, icon = self.get_star_rating(final_score)
|
180 |
+
explanation = self.generate_explanation(domain_trust, similarity_score, fact_check_score, bias_score, citation_score, safe_browsing_score, final_score)
|
181 |
+
|
182 |
+
return {
|
183 |
+
"raw_score": {
|
184 |
+
"Domain Trust": domain_trust,
|
185 |
+
"Content Relevance": similarity_score,
|
186 |
+
"Fact-Check Score": fact_check_score,
|
187 |
+
"Bias Score": bias_score,
|
188 |
+
"Citation Score": citation_score,
|
189 |
+
"Safe Browsing Score": safe_browsing_score,
|
190 |
+
"Final Validity Score": final_score
|
191 |
+
},
|
192 |
+
"stars": {
|
193 |
+
"score": stars,
|
194 |
+
"icon": icon
|
195 |
+
},
|
196 |
+
"explanation": explanation
|
197 |
+
}
|
198 |
+
|
199 |
+
|
200 |
+
st.title("URL Validator")
|
201 |
+
|
202 |
+
# Input fields for user prompt and URL
|
203 |
+
user_prompt = st.text_input("Enter your query:", placeholder="e.g., What mods should I use on Volt Prime?")
|
204 |
+
url_to_check = st.text_input("Enter URL to validate:", placeholder="e.g., https://overframe.gg/items/arsenal/61/volt-prime/")
|
205 |
+
|
206 |
+
# Run validation on button click
|
207 |
+
if st.button("Validate URL"):
|
208 |
+
if user_prompt and url_to_check:
|
209 |
+
validator = URLValidator()
|
210 |
+
result = validator.rate_url_validity(user_prompt, url_to_check)
|
211 |
+
|
212 |
+
st.subheader("Validation Results")
|
213 |
+
st.json(result) # Display JSON object
|
214 |
+
else:
|
215 |
+
st.warning("Please enter both a query and a URL.")
|
216 |
|
217 |
|
|
requirements.txt
CHANGED
@@ -1 +1,7 @@
|
|
1 |
-
streamlit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
requests
|
3 |
+
beautifulsoup4
|
4 |
+
sentence-transformers
|
5 |
+
transformers
|
6 |
+
torch
|
7 |
+
os
|