FariaNoumi09 commited on
Commit
1a3675b
·
1 Parent(s): 9e3ce60

First Commit of App

Browse files
Files changed (2) hide show
  1. app.py +167 -1
  2. requirements.txt +4 -0
app.py CHANGED
@@ -1,3 +1,169 @@
 
1
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  st.write("LEVEL1 TITLE: APP")
3
- st.write ("This is my first app")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # This api key is acquired from SerpAPI website.
18
+ self.serpapi_key = os.getenv("SERPAPI_KEY")
19
+
20
+ # Load models once to avoid redundant API calls
21
+ self.similarity_model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')
22
+ self.fake_news_classifier = pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection")
23
+ self.sentiment_analyzer = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment")
24
+
25
+ def fetch_page_content(self, url: str) -> str:
26
+ """ Fetches and extracts text content from the given URL. """
27
+ try:
28
+ response = requests.get(url, timeout=10)
29
+ response.raise_for_status()
30
+ soup = BeautifulSoup(response.text, "html.parser")
31
+ return " ".join([p.text for p in soup.find_all("p")]) # Extract paragraph text
32
+ except requests.RequestException:
33
+ return "" # Fail gracefully by returning an empty string
34
+
35
+ def get_domain_trust(self, url: str, content: str) -> int:
36
+ """ Computes the domain trust score based on available data sources. """
37
+ trust_scores = []
38
+
39
+ # Hugging Face Fake News Detector
40
+ if content:
41
+ try:
42
+ trust_scores.append(self.get_domain_trust_huggingface(content))
43
+ except:
44
+ pass
45
+
46
+ # Compute final score (average of available scores)
47
+ return int(sum(trust_scores) / len(trust_scores)) if trust_scores else 50
48
+
49
+ def get_domain_trust_huggingface(self, content: str) -> int:
50
+ """ Uses a Hugging Face fake news detection model to assess credibility. """
51
+ if not content:
52
+ return 50 # Default score if no content available
53
+ result = self.fake_news_classifier(content[:512])[0] # Process only first 512 characters
54
+ return 100 if result["label"] == "REAL" else 30 if result["label"] == "FAKE" else 50
55
+
56
+ def compute_similarity_score(self, user_query: str, content: str) -> int:
57
+ """ Computes semantic similarity between user query and page content. """
58
+ if not content:
59
+ return 0
60
+ return int(util.pytorch_cos_sim(self.similarity_model.encode(user_query), self.similarity_model.encode(content)).item() * 100)
61
+
62
+ def check_facts(self, content: str) -> int:
63
+ """ Cross-checks extracted content with Google Fact Check API. """
64
+ if not content:
65
+ return 50
66
+ api_url = f"https://toolbox.google.com/factcheck/api/v1/claimsearch?query={content[:200]}"
67
+ try:
68
+ response = requests.get(api_url)
69
+ data = response.json()
70
+ return 80 if "claims" in data and data["claims"] else 40
71
+ except:
72
+ return 50 # Default uncertainty score
73
+
74
+ def check_google_scholar(self, url: str) -> int:
75
+ """ Checks Google Scholar citations using SerpAPI. """
76
+ serpapi_key = self.serpapi_key
77
+ params = {"q": url, "engine": "google_scholar", "api_key": serpapi_key}
78
+ try:
79
+ response = requests.get("https://serpapi.com/search", params=params)
80
+ data = response.json()
81
+ return min(len(data.get("organic_results", [])) * 10, 100) # Normalize
82
+ except:
83
+ return 0 # Default to no citations
84
+
85
+ def detect_bias(self, content: str) -> int:
86
+ """ Uses NLP sentiment analysis to detect potential bias in content. """
87
+ if not content:
88
+ return 50
89
+ sentiment_result = self.sentiment_analyzer(content[:512])[0]
90
+ return 100 if sentiment_result["label"] == "POSITIVE" else 50 if sentiment_result["label"] == "NEUTRAL" else 30
91
+
92
+ def get_star_rating(self, score: float) -> tuple:
93
+ """ Converts a score (0-100) into a 1-5 star rating. """
94
+ stars = max(1, min(5, round(score / 20))) # Normalize 100-scale to 5-star scale
95
+ return stars, "⭐" * stars
96
+
97
+ def generate_explanation(self, domain_trust, similarity_score, fact_check_score, bias_score, citation_score, final_score) -> str:
98
+ """ Generates a human-readable explanation for the score. """
99
+ reasons = []
100
+ if domain_trust < 50:
101
+ reasons.append("The source has low domain authority.")
102
+ if similarity_score < 50:
103
+ reasons.append("The content is not highly relevant to your query.")
104
+ if fact_check_score < 50:
105
+ reasons.append("Limited fact-checking verification found.")
106
+ if bias_score < 50:
107
+ reasons.append("Potential bias detected in the content.")
108
+ if citation_score < 30:
109
+ reasons.append("Few citations found for this content.")
110
+
111
+ return " ".join(reasons) if reasons else "This source is highly credible and relevant."
112
+
113
+ def rate_url_validity(self, user_query: str, url: str) -> dict:
114
+ """ Main function to evaluate the validity of a webpage. """
115
+ content = self.fetch_page_content(url)
116
+
117
+ domain_trust = self.get_domain_trust(url, content)
118
+ similarity_score = self.compute_similarity_score(user_query, content)
119
+ fact_check_score = self.check_facts(content)
120
+ bias_score = self.detect_bias(content)
121
+ citation_score = self.check_google_scholar(url)
122
+
123
+ final_score = (
124
+ (0.3 * domain_trust) +
125
+ (0.3 * similarity_score) +
126
+ (0.2 * fact_check_score) +
127
+ (0.1 * bias_score) +
128
+ (0.1 * citation_score)
129
+ )
130
+
131
+ stars, icon = self.get_star_rating(final_score)
132
+ explanation = self.generate_explanation(domain_trust, similarity_score, fact_check_score, bias_score, citation_score, final_score)
133
+
134
+ return {
135
+ "raw_score": {
136
+ "Domain Trust": domain_trust,
137
+ "Content Relevance": similarity_score,
138
+ "Fact-Check Score": fact_check_score,
139
+ "Bias Score": bias_score,
140
+ "Citation Score": citation_score,
141
+ "Final Validity Score": final_score
142
+ },
143
+ "stars": {
144
+ "score": stars,
145
+ "icon": icon
146
+ },
147
+ "explanation": explanation
148
+ }
149
+
150
  st.write("LEVEL1 TITLE: APP")
151
+ st.write ("This is my first app")
152
+
153
+ # User input fields
154
+ user_prompt = "I have just been on an international flight, can I come back home to hold my 1-month-old newborn?"
155
+ url_to_check = "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)
requirements.txt CHANGED
@@ -1 +1,5 @@
1
  streamlit
 
 
 
 
 
1
  streamlit
2
+ requests
3
+ beautifulsoup4
4
+ sentence-transformers transformers
5
+ torch