mh21492p commited on
Commit
fa36ee8
·
verified ·
1 Parent(s): 325de0c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -0
app.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+
4
+ import requests
5
+ from bs4 import BeautifulSoup
6
+ from sentence_transformers import SentenceTransformer, util
7
+ from transformers import pipeline
8
+
9
+ class URLValidator:
10
+ """
11
+ A production-ready URL validation class that evaluates the credibility of a webpage
12
+ using multiple factors: domain trust, content relevance, fact-checking, bias detection, and citations.
13
+ """
14
+
15
+ def __init__(self):
16
+ # SerpAPI Key
17
+ self.serpapi_key = os.getenv("SERPAPI_API_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, 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
+ if similarity_score < 50:
102
+ reasons.append("The content is not highly relevant to your query.")
103
+ if fact_check_score < 50:
104
+ reasons.append("Limited fact-checking verification found.")
105
+ if bias_score < 50:
106
+ reasons.append("Potential bias detected in the content.")
107
+ if citation_score < 30:
108
+ reasons.append("Few citations found for this content.")
109
+
110
+ return " ".join(reasons) if reasons else "This source is highly credible and relevant."
111
+
112
+ def rate_url_validity(self, user_query: str, url: str) -> dict:
113
+ """ Main function to evaluate the validity of a webpage. """
114
+ content = self.fetch_page_content(url)
115
+
116
+ domain_trust = self.get_domain_trust(url, content)
117
+ similarity_score = self.compute_similarity_score(user_query, content)
118
+ fact_check_score = self.check_facts(content)
119
+ bias_score = self.detect_bias(content)
120
+ citation_score = self.check_google_scholar(url)
121
+
122
+ final_score = (
123
+ (0.3 * domain_trust) +
124
+ (0.3 * similarity_score) +
125
+ (0.2 * fact_check_score) +
126
+ (0.1 * bias_score) +
127
+ (0.1 * citation_score)
128
+ )
129
+
130
+ stars, icon = self.get_star_rating(final_score)
131
+ explanation = self.generate_explanation(domain_trust, similarity_score, fact_check_score, bias_score, citation_score, final_score)
132
+
133
+ return {
134
+ "raw_score": {
135
+ "Domain Trust": domain_trust,
136
+ "Content Relevance": similarity_score,
137
+ "Fact-Check Score": fact_check_score,
138
+ "Bias Score": bias_score,
139
+ "Citation Score": citation_score,
140
+ "Final Validity Score": final_score
141
+ },
142
+ "stars": {
143
+ "score": stars,
144
+ "icon": icon
145
+ },
146
+ "explanation": explanation
147
+ }
148
+
149
+
150
+ st.write("# LEVEL1 TITLE: APP")
151
+ st.write("this is my first app")
152
+
153
+ # User input fields
154
+ user_prompt = st.text_area("Enter your search query:", "I have just been on an international flight, can I come back home to hold my 1-month-old newborn?")
155
+ url_to_check = st.text_input("Enter the URL to validate:", "https://www.mayoclinic.org/healthy-lifestyle/infant-and-toddler-health/expert-answers/air-travel-with-infant/faq-20058539")
156
+
157
+ # Run validation when the button is clicked
158
+ if st.button("Validate URL"):
159
+ if not user_prompt.strip() or not url_to_check.strip():
160
+ st.warning("Please enter both a search query and a URL.")
161
+ else:
162
+ with st.spinner("Validating URL..."):
163
+ # Instantiate the URLValidator class
164
+ validator = URLValidator()
165
+ result = validator.rate_url_validity(user_prompt, url_to_check)
166
+
167
+ # Display results in JSON format
168
+ st.subheader("Validation Results")
169
+ st.json(result)
170
+