Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
# imports
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import urllib.parse
|
| 5 |
-
import concurrent.futures
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
import streamlit as st
|
| 8 |
-
from groq import Groq
|
| 9 |
from textblob import TextBlob
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import textstat
|
| 11 |
import trafilatura
|
| 12 |
import requests
|
|
@@ -16,35 +17,14 @@ import nltk
|
|
| 16 |
# constants
|
| 17 |
MAX_WORDS = 400
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
# Initialize the
|
| 22 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 23 |
-
|
| 24 |
-
client = Groq(api_key=GROQ_API_KEY)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
@st.cache_data(ttl=3600, show_spinner=False)
|
| 28 |
-
def fetch_topic_news(query: str, limit: int = 8) -> list:
|
| 29 |
-
"""Fetches news articles for a topic using Google News RSS."""
|
| 30 |
-
encoded_query = urllib.parse.quote(query)
|
| 31 |
-
rss_url = f"https://news.google.com/rss/search?q={encoded_query}&hl=en-US&gl=US&ceid=US:en"
|
| 32 |
-
|
| 33 |
-
try:
|
| 34 |
-
response = requests.get(rss_url, timeout=10)
|
| 35 |
-
soup = BeautifulSoup(response.content, features="xml")
|
| 36 |
-
items = soup.findAll('item')[:limit]
|
| 37 |
-
|
| 38 |
-
articles = []
|
| 39 |
-
for item in items:
|
| 40 |
-
articles.append({
|
| 41 |
-
"publisher": item.source.text if item.source else "Unknown Outlet",
|
| 42 |
-
"title": item.title.text,
|
| 43 |
-
"url": item.link.text
|
| 44 |
-
})
|
| 45 |
-
return articles
|
| 46 |
-
except Exception as e:
|
| 47 |
-
return []
|
| 48 |
|
| 49 |
def _truncate_to_words(text: str, limit: int) -> str:
|
| 50 |
"""Truncates text by word count."""
|
|
@@ -82,9 +62,11 @@ def analyze_article(text: str) -> dict:
|
|
| 82 |
Text to analyze:
|
| 83 |
"{safe_text}"
|
| 84 |
"""
|
|
|
|
|
|
|
| 85 |
response = client.chat.completions.create(
|
| 86 |
model="llama-3.3-70b-versatile",
|
| 87 |
-
messages=
|
| 88 |
max_tokens=300,
|
| 89 |
temperature=0.1,
|
| 90 |
response_format={"type": "json_object"}
|
|
@@ -94,26 +76,96 @@ def analyze_article(text: str) -> dict:
|
|
| 94 |
subjectivity_score = TextBlob(safe_text).sentiment.subjectivity
|
| 95 |
raw_reading_ease = textstat.flesch_reading_ease(safe_text)
|
| 96 |
|
| 97 |
-
tones = llm_data.get("tone_scores", {})
|
| 98 |
-
standard_tones = {
|
| 99 |
-
"anger": tones.get("anger", 0.0),
|
| 100 |
-
"fear": tones.get("fear", 0.0),
|
| 101 |
-
"joy": tones.get("joy", 0.0),
|
| 102 |
-
"sadness": tones.get("sadness", 0.0),
|
| 103 |
-
"surprise": tones.get("surprise", 0.0),
|
| 104 |
-
"trust": tones.get("trust", 0.0),
|
| 105 |
-
}
|
| 106 |
-
|
| 107 |
return {
|
| 108 |
"sentiment_score": llm_data.get("sentiment_score", 0.0),
|
| 109 |
"primary_tone": llm_data.get("primary_tone", "neutral"),
|
| 110 |
"primary_theme": llm_data.get("primary_theme", "unclear"),
|
| 111 |
-
"tone_scores":
|
| 112 |
"framing_words": llm_data.get("framing_words", []),
|
| 113 |
"subjectivity_score": subjectivity_score,
|
| 114 |
"reading_ease": max(0.0, min(100.0, raw_reading_ease)),
|
| 115 |
}
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
@st.cache_data(ttl=3600, show_spinner=False)
|
| 118 |
def fetch_article_text(url: str) -> str:
|
| 119 |
"""Scrapes article text."""
|
|
@@ -145,103 +197,181 @@ def fetch_article_text(url: str) -> str:
|
|
| 145 |
|
| 146 |
return "Error: Could not extract text. The site may be protected by hard paywalls."
|
| 147 |
|
| 148 |
-
def _create_macro_scatter_plot(results: list) -> go.Figure:
|
| 149 |
-
"""Generates a scatter plot of multiple media outlets."""
|
| 150 |
-
fig = go.Figure()
|
| 151 |
-
|
| 152 |
-
color_map = {
|
| 153 |
-
"economic consequences": "#3b82f6",
|
| 154 |
-
"moral and ethical fairness": "#10b981",
|
| 155 |
-
"legal and bureaucratic": "#f59e0b",
|
| 156 |
-
"public safety and health": "#ef4444",
|
| 157 |
-
"unclear": "#64748b"
|
| 158 |
-
}
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
yaxis_title="Subjectivity (Objective to Opinionated)",
|
| 184 |
-
xaxis=dict(range=[-1.1, 1.1], zeroline=True, zerolinewidth=2, zerolinecolor='rgba(0,0,0,0.2)'),
|
| 185 |
-
yaxis=dict(range=[-0.1, 1.1], zeroline=True, zerolinewidth=2, zerolinecolor='rgba(0,0,0,0.2)'),
|
| 186 |
-
height=600,
|
| 187 |
-
plot_bgcolor='#f8fafc'
|
| 188 |
)
|
| 189 |
-
return fig
|
| 190 |
-
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
if not GROQ_API_KEY:
|
| 193 |
st.warning("Groq API Token Missing.")
|
| 194 |
st.stop()
|
| 195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
# STATE MANAGEMENT
|
| 197 |
-
if "
|
| 198 |
-
st.session_state.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
else:
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
st.session_state.batch_results = processed_results
|
| 236 |
-
|
| 237 |
-
# Macro Analysis
|
| 238 |
-
if st.session_state.batch_results:
|
| 239 |
st.divider()
|
| 240 |
-
st.
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
st.
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# imports
|
| 2 |
+
import re
|
| 3 |
+
import typing
|
|
|
|
|
|
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
import streamlit as st
|
|
|
|
| 6 |
from textblob import TextBlob
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import concurrent.futures
|
| 10 |
+
from groq import Groq
|
| 11 |
import textstat
|
| 12 |
import trafilatura
|
| 13 |
import requests
|
|
|
|
| 17 |
# constants
|
| 18 |
MAX_WORDS = 400
|
| 19 |
|
| 20 |
+
ARTICLE_A = """In a watershed moment for global tech governance, international regulatory bodies have introduced the comprehensive Artificial Intelligence Safeguard Act. For too long, Silicon Valley titans have operated in a wild west environment, prioritizing unchecked corporate greed and rapid deployment over public safety. This landmark legislation aims to establish rigorous ethical boundaries and mandatory safety audits before any advanced generative models can be released to the public. Proponents argue that without these essential guardrails, society faces catastrophic risks ranging from massive, unmitigated job displacement to the proliferation of deepfake-fueled misinformation that threatens the very fabric of our democratic institutions. "We cannot allow a handful of unelected tech billionaires to play roulette with humanity's future," stated the coalition's lead ethicist. By prioritizing human welfare over blind technological acceleration, the Act serves as a vital moral firewall, ensuring that the development of artificial general intelligence benefits society as a whole rather than just enriching the elite few."""
|
| 21 |
+
ARTICLE_B = """Tech industry leaders and economists are sounding the alarm over the newly proposed Artificial Intelligence Safeguard Act, warning that the draconian legislation will severely cripple the nation’s economic engine. Critics argue that the bill is a masterclass in bureaucratic overreach, drowning agile tech startups in layers of punitive red tape and effectively stifling the very innovation that drives modern prosperity. By mandating arbitrary algorithmic audits and imposing heavy-handed restrictions on model training, the government is poised to surrender our global competitive edge to foreign adversaries who are not bound by such paralyzing regulations. "This isn't about safety; it's an innovation tax that penalizes success," argued a prominent venture capitalist. Analysts project that this short-sighted policy will force thousands of AI researchers to relocate overseas, draining billions of dollars in investment capital from the domestic market. Ultimately, framing technological progress as an inherent danger will only succeed in legislating the industry into obsolescence, destroying millions of future private-sector jobs in the process."""
|
| 22 |
+
URL_A = "https://www.foxnews.com/live-news/trump-iran-israel-war-updates-march-30"
|
| 23 |
+
URL_B = "https://edition.cnn.com/2026/03/30/world/live-news/iran-war-us-israel-trump"
|
| 24 |
|
| 25 |
+
# Initialize the Hugging Face Client
|
| 26 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 27 |
+
client = Groq(api_key=GROQ_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def _truncate_to_words(text: str, limit: int) -> str:
|
| 30 |
"""Truncates text by word count."""
|
|
|
|
| 62 |
Text to analyze:
|
| 63 |
"{safe_text}"
|
| 64 |
"""
|
| 65 |
+
|
| 66 |
+
messages = [{"role": "user", "content": prompt}]
|
| 67 |
response = client.chat.completions.create(
|
| 68 |
model="llama-3.3-70b-versatile",
|
| 69 |
+
messages=messages,
|
| 70 |
max_tokens=300,
|
| 71 |
temperature=0.1,
|
| 72 |
response_format={"type": "json_object"}
|
|
|
|
| 76 |
subjectivity_score = TextBlob(safe_text).sentiment.subjectivity
|
| 77 |
raw_reading_ease = textstat.flesch_reading_ease(safe_text)
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
return {
|
| 80 |
"sentiment_score": llm_data.get("sentiment_score", 0.0),
|
| 81 |
"primary_tone": llm_data.get("primary_tone", "neutral"),
|
| 82 |
"primary_theme": llm_data.get("primary_theme", "unclear"),
|
| 83 |
+
"tone_scores": llm_data.get("tone_scores", {"anger": 0, "fear": 0, "joy": 0, "sadness": 0, "surprise": 0, "trust": 0}),
|
| 84 |
"framing_words": llm_data.get("framing_words", []),
|
| 85 |
"subjectivity_score": subjectivity_score,
|
| 86 |
"reading_ease": max(0.0, min(100.0, raw_reading_ease)),
|
| 87 |
}
|
| 88 |
|
| 89 |
+
|
| 90 |
+
def _create_sentiment_gauge(score: float, title: str) -> go.Figure:
|
| 91 |
+
"""Generates a Plotly gauge chart for sentiment visualization."""
|
| 92 |
+
fig = go.Figure(
|
| 93 |
+
go.Indicator(
|
| 94 |
+
mode="gauge+number",
|
| 95 |
+
value=score,
|
| 96 |
+
domain={"x": [0, 1], "y": [0, 1]},
|
| 97 |
+
title={"text": title, "font": {"size": 16}},
|
| 98 |
+
gauge={
|
| 99 |
+
"axis": {"range": [-1, 1], "tickwidth": 1, "tickcolor": "darkgrey"},
|
| 100 |
+
"bar": {"color": "#475569", "thickness": 0.2},
|
| 101 |
+
"bgcolor": "white",
|
| 102 |
+
"borderwidth": 0,
|
| 103 |
+
"steps": [
|
| 104 |
+
{"range": [-1, -0.1], "color": "#fee2e2"},
|
| 105 |
+
{"range": [-0.1, 0.1], "color": "#f1f5f9"},
|
| 106 |
+
{"range": [0.1, 1], "color": "#dcfce3"},
|
| 107 |
+
],
|
| 108 |
+
},
|
| 109 |
+
)
|
| 110 |
+
)
|
| 111 |
+
fig.update_layout(height=280, margin=dict(l=20, r=20, t=60, b=20))
|
| 112 |
+
return fig
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _create_comparison_radar_chart(results_a: dict, results_b: dict) -> go.Figure:
|
| 116 |
+
"""Generates an overlapping radar chart to compare emotions."""
|
| 117 |
+
categories = sorted(list(set(list(results_a["tone_scores"].keys()) + list(results_b["tone_scores"].keys()))))
|
| 118 |
+
|
| 119 |
+
val_a = [results_a["tone_scores"].get(c, 0) for c in categories]
|
| 120 |
+
val_b = [results_b["tone_scores"].get(c, 0) for c in categories]
|
| 121 |
+
|
| 122 |
+
categories.append(categories[0])
|
| 123 |
+
val_a.append(val_a[0])
|
| 124 |
+
val_b.append(val_b[0])
|
| 125 |
+
|
| 126 |
+
fig = go.Figure()
|
| 127 |
+
fig.add_trace(go.Scatterpolar(
|
| 128 |
+
r=val_a, theta=categories, fill='toself', name='Source A',
|
| 129 |
+
line=dict(color='#4f46e5', shape='spline', width=2),
|
| 130 |
+
fillcolor='rgba(79, 70, 229, 0.2)'
|
| 131 |
+
))
|
| 132 |
+
fig.add_trace(go.Scatterpolar(
|
| 133 |
+
r=val_b, theta=categories, fill='toself', name='Source B',
|
| 134 |
+
line=dict(color='#10b981', shape='spline', width=2),
|
| 135 |
+
fillcolor='rgba(16, 185, 129, 0.2)'
|
| 136 |
+
))
|
| 137 |
+
fig.update_layout(
|
| 138 |
+
polar=dict(
|
| 139 |
+
radialaxis=dict(visible=True, showticklabels=False, showline=False, gridcolor='rgba(0,0,0,0.1)'),
|
| 140 |
+
angularaxis=dict(gridcolor='rgba(0,0,0,0.1)', linecolor='rgba(0,0,0,0.1)')
|
| 141 |
+
),
|
| 142 |
+
showlegend=True,
|
| 143 |
+
legend=dict(orientation="h", yanchor="bottom", y=-0.2, xanchor="center", x=0.5),
|
| 144 |
+
title={"text": "Relative Emotion Profile", "font": {"size": 18, "family": "sans-serif"}},
|
| 145 |
+
height=400,
|
| 146 |
+
margin=dict(l=40, r=40, t=60, b=40),
|
| 147 |
+
paper_bgcolor='rgba(0,0,0,0)', # Transparent
|
| 148 |
+
plot_bgcolor='rgba(0,0,0,0)'
|
| 149 |
+
)
|
| 150 |
+
return fig
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _highlight_framing_words(text: str, target_words: list) -> str:
|
| 154 |
+
"""Highlights LLM-identified framing words in the synced text snippet."""
|
| 155 |
+
display_text = _truncate_to_words(text, MAX_WORDS)
|
| 156 |
+
if not display_text:
|
| 157 |
+
return ""
|
| 158 |
+
|
| 159 |
+
highlighted_text = display_text + ("..." if len(text.split()) > MAX_WORDS else "")
|
| 160 |
+
|
| 161 |
+
for word in target_words:
|
| 162 |
+
if len(word) > 2:
|
| 163 |
+
pattern = r'\b(' + re.escape(word) + r')\b'
|
| 164 |
+
replacement = r"<span style='background-color: #fef08a; color: #854d0e; font-weight: 600; padding: 0.1rem 0.2rem; border-radius: 4px;'>\1</span>"
|
| 165 |
+
highlighted_text = re.sub(pattern, replacement, highlighted_text, flags=re.IGNORECASE)
|
| 166 |
+
|
| 167 |
+
return highlighted_text
|
| 168 |
+
|
| 169 |
@st.cache_data(ttl=3600, show_spinner=False)
|
| 170 |
def fetch_article_text(url: str) -> str:
|
| 171 |
"""Scrapes article text."""
|
|
|
|
| 197 |
|
| 198 |
return "Error: Could not extract text. The site may be protected by hard paywalls."
|
| 199 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
def check_contradiction(text_a: str, text_b: str) -> dict:
|
| 202 |
+
"""Uses the LLM to evaluate the stance between arguments."""
|
| 203 |
+
safe_a = _truncate_to_words(text_a, MAX_WORDS)
|
| 204 |
+
safe_b = _truncate_to_words(text_b, MAX_WORDS)
|
| 205 |
+
|
| 206 |
+
prompt = f"""
|
| 207 |
+
You are a fact-checking analyst. Compare these two news excerpts.
|
| 208 |
+
Return ONLY a valid JSON object with the exact keys below. Do not include markdown formatting.
|
| 209 |
+
|
| 210 |
+
Keys to return:
|
| 211 |
+
"relationship": Choose ONE from: ["CONTRADICTION", "ENTAILMENT", "NEUTRAL"]. (Contradiction = disputing facts, Entailment = agreeing on premise).
|
| 212 |
+
"confidence": A float between 0.0 and 1.0 representing how confident you are.
|
| 213 |
+
|
| 214 |
+
Text 1: "{safe_a}"
|
| 215 |
+
Text 2: "{safe_b}"
|
| 216 |
+
"""
|
| 217 |
+
messages = [{"role": "user", "content": prompt}]
|
| 218 |
+
response = client.chat.completions.create(
|
| 219 |
+
model="llama-3.3-70b-versatile",
|
| 220 |
+
messages=messages,
|
| 221 |
+
max_tokens=100,
|
| 222 |
+
temperature=0.1,
|
| 223 |
+
response_format={"type": "json_object"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
)
|
|
|
|
|
|
|
| 225 |
|
| 226 |
+
result = json.loads(response.choices[0].message.content)
|
| 227 |
+
return {"relationship": result.get("relationship", "NEUTRAL"), "confidence": result.get("confidence", 0.0)}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# USER INTERFACE
|
| 231 |
+
st.set_page_config(page_title="FrameVis | Media Framing", layout="wide")
|
| 232 |
+
|
| 233 |
if not GROQ_API_KEY:
|
| 234 |
st.warning("Groq API Token Missing.")
|
| 235 |
st.stop()
|
| 236 |
|
| 237 |
+
st.markdown("""
|
| 238 |
+
<style>
|
| 239 |
+
#MainMenu {visibility: hidden;}
|
| 240 |
+
footer {visibility: hidden;}
|
| 241 |
+
header {visibility: hidden;}
|
| 242 |
+
|
| 243 |
+
.block-container {
|
| 244 |
+
padding-top: 2rem;
|
| 245 |
+
padding-bottom: 2rem;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
[data-testid="stMetric"] {
|
| 249 |
+
background-color: #f8fafc;
|
| 250 |
+
border: 1px solid #e2e8f0;
|
| 251 |
+
border-radius: 8px;
|
| 252 |
+
padding: 15px;
|
| 253 |
+
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
[data-testid="stMetricValue"] > div {
|
| 257 |
+
white-space: normal !important;
|
| 258 |
+
word-wrap: break-word !important;
|
| 259 |
+
line-height: 1.2 !important;
|
| 260 |
+
font-size: 1.6rem !important;
|
| 261 |
+
}
|
| 262 |
+
</style>
|
| 263 |
+
""", unsafe_allow_html=True)
|
| 264 |
+
|
| 265 |
# STATE MANAGEMENT
|
| 266 |
+
if "results_a" not in st.session_state:
|
| 267 |
+
st.session_state.results_a = None
|
| 268 |
+
if "results_b" not in st.session_state:
|
| 269 |
+
st.session_state.results_b = None
|
| 270 |
+
if "nli_result" not in st.session_state:
|
| 271 |
+
st.session_state.nli_result = None
|
| 272 |
|
| 273 |
+
st.title("FrameVis")
|
| 274 |
+
st.markdown("##### Media bias and framing effects across global news sources.")
|
| 275 |
+
st.divider()
|
| 276 |
|
| 277 |
+
input_method = st.radio("Input Method", ["Paste Text", "Paste URL"], horizontal=True, index=0)
|
| 278 |
+
|
| 279 |
+
col1, col2 = st.columns(2)
|
| 280 |
+
|
| 281 |
+
with col1:
|
| 282 |
+
if input_method == "Paste Text":
|
| 283 |
+
user_article_a = st.text_area("Data Source A", value=ARTICLE_A.strip(), height=220)
|
| 284 |
else:
|
| 285 |
+
url_a = st.text_input("Source A URL", value=URL_A)
|
| 286 |
+
user_article_a = fetch_article_text(url_a) if url_a else ""
|
| 287 |
+
|
| 288 |
+
with col2:
|
| 289 |
+
if input_method == "Paste Text":
|
| 290 |
+
user_article_b = st.text_area("Data Source B", value=ARTICLE_B.strip(), height=220)
|
| 291 |
+
else:
|
| 292 |
+
url_b = st.text_input("Source B URL", value=URL_B)
|
| 293 |
+
user_article_b = fetch_article_text(url_b) if url_b else ""
|
| 294 |
+
|
| 295 |
+
st.write("")
|
| 296 |
+
|
| 297 |
+
# Execution button
|
| 298 |
+
if st.button("Analyze and Compare Sources", use_container_width=True, type="primary"):
|
| 299 |
+
|
| 300 |
+
text_a_clean = user_article_a.strip() if user_article_a else ""
|
| 301 |
+
text_b_clean = user_article_b.strip() if user_article_b else ""
|
| 302 |
+
|
| 303 |
+
if not text_a_clean or not text_b_clean:
|
| 304 |
+
st.warning("Please provide text or a valid URL for both Source A and Source B before analyzing.")
|
| 305 |
+
|
| 306 |
+
elif text_a_clean.startswith("Error:") or text_b_clean.startswith("Error:"):
|
| 307 |
+
st.error("One of the URLs could not be scraped. Please copy and paste the text directly.")
|
| 308 |
+
|
| 309 |
+
else:
|
| 310 |
+
with st.spinner("Analyzing framing semantics for both sources."):
|
| 311 |
+
try:
|
| 312 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 313 |
+
future_a = executor.submit(analyze_article, text_a_clean)
|
| 314 |
+
future_b = executor.submit(analyze_article, text_b_clean)
|
| 315 |
+
future_nli = executor.submit(check_contradiction, text_a_clean, text_b_clean)
|
| 316 |
|
| 317 |
+
st.session_state.results_a = future_a.result()
|
| 318 |
+
st.session_state.results_b = future_b.result()
|
| 319 |
+
st.session_state.nli_result = future_nli.result()
|
| 320 |
+
except Exception as e:
|
| 321 |
+
st.error(f"API or Processing Error: {str(e)}")
|
| 322 |
+
st.session_state.results_a = None
|
| 323 |
+
st.session_state.results_b = None
|
| 324 |
+
st.session_state.nli_result = None
|
| 325 |
+
|
| 326 |
+
# Analysis Display
|
| 327 |
+
if st.session_state.results_a and st.session_state.results_b:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
st.divider()
|
| 329 |
+
st.markdown("### Framing Analytics & Comparison")
|
| 330 |
+
|
| 331 |
+
# Display Contradictions
|
| 332 |
+
nli_result = st.session_state.nli_result
|
| 333 |
+
if nli_result:
|
| 334 |
+
if nli_result["relationship"].upper() == "CONTRADICTION":
|
| 335 |
+
st.error(f"**NARRATIVE CONTRADICTION** (Confidence: {nli_result['confidence']:.2f}) - These sources are disputing each other's facts.")
|
| 336 |
+
elif nli_result["relationship"].upper() == "ENTAILMENT":
|
| 337 |
+
st.success(f"**NARRATIVE ALIGNMENT** (Confidence: {nli_result['confidence']:.2f}) - These sources agree on the core premise.")
|
| 338 |
+
else:
|
| 339 |
+
st.info(f"**NEUTRAL RELATIONSHIP** - These sources are discussing the topic without direct contradiction or alignment.")
|
| 340 |
+
|
| 341 |
+
st.plotly_chart(_create_comparison_radar_chart(st.session_state.results_a, st.session_state.results_b), use_container_width=True)
|
| 342 |
+
|
| 343 |
+
res_col1, res_col2 = st.columns(2)
|
| 344 |
+
|
| 345 |
+
# Render Column A
|
| 346 |
+
with res_col1:
|
| 347 |
+
r_a = st.session_state.results_a
|
| 348 |
+
st.markdown("#### Source A Breakdown")
|
| 349 |
+
m1, m2 = st.columns(2)
|
| 350 |
+
m3, m4 = st.columns(2)
|
| 351 |
+
m1.metric("Subjectivity", f"{r_a['subjectivity_score']:.2f}", help="0 is objective, 1 is highly opinionated.")
|
| 352 |
+
m2.metric("Primary Emotion", str(r_a['primary_tone']).title())
|
| 353 |
+
m3.metric("Framing Lens", str(r_a['primary_theme']).title())
|
| 354 |
+
m4.metric("Reading Ease", f"{r_a['reading_ease']:.1f}", help="0-30 is college graduate level, 60-70 is 8th grade.")
|
| 355 |
+
|
| 356 |
+
st.plotly_chart(_create_sentiment_gauge(r_a["sentiment_score"], "Sentiment Bias"), use_container_width=True, key="gauge_a")
|
| 357 |
+
|
| 358 |
+
st.markdown("**Key Framing Language:**")
|
| 359 |
+
annotated_text = _highlight_framing_words(user_article_a, r_a['framing_words'])
|
| 360 |
+
st.markdown(f"<div style='background-color: #f8fafc; padding: 1rem; border-radius: 8px; border: 1px solid #e2e8f0;'>{annotated_text}</div>", unsafe_allow_html=True)
|
| 361 |
+
|
| 362 |
+
# Render Column B
|
| 363 |
+
with res_col2:
|
| 364 |
+
r_b = st.session_state.results_b
|
| 365 |
+
st.markdown("#### Source B Breakdown")
|
| 366 |
+
m1, m2 = st.columns(2)
|
| 367 |
+
m3, m4 = st.columns(2)
|
| 368 |
+
m1.metric("Subjectivity", f"{r_b['subjectivity_score']:.2f}", help="0 is objective, 1 is highly opinionated.")
|
| 369 |
+
m2.metric("Primary Emotion", str(r_b['primary_tone']).title())
|
| 370 |
+
m3.metric("Framing Lens", str(r_b['primary_theme']).title())
|
| 371 |
+
m4.metric("Reading Ease", f"{r_b['reading_ease']:.1f}", help="0-30 is college graduate level, 60-70 is 8th grade.")
|
| 372 |
+
|
| 373 |
+
st.plotly_chart(_create_sentiment_gauge(r_b["sentiment_score"], "Sentiment Bias"), use_container_width=True, key="gauge_b")
|
| 374 |
+
|
| 375 |
+
st.markdown("**Key Framing Language:**")
|
| 376 |
+
annotated_text = _highlight_framing_words(user_article_b, r_b['framing_words'])
|
| 377 |
+
st.markdown(f"<div style='background-color: #f8fafc; padding: 1rem; border-radius: 8px; border: 1px solid #e2e8f0;'>{annotated_text}</div>", unsafe_allow_html=True)
|