nicholassarni commited on
Commit
2e079f2
·
1 Parent(s): e9ad6fc

first commit of app

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