Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181 unmodified line20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112123 unmodified lines2162172182192202212226 unmodified lines229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399# importsimport reimport typingimport plotly.graph_objects as goimport streamlit as stfrom textblob import TextBlobfrom transformers import pipelineimport textstatimport trafilaturaimport requestsfrom bs4 import BeautifulSoupimport nltk# constantsMAX_TEXT_LENGTH = 1500ARTICLE_A = """In a long-overdue victory for working-class families, lawmakers unveiled a bold new wealth tax targeting the nation's ultra-rich. For decades, billionaires have exploited gaping loopholes to hoard unprecedented wealth while paying a fraction of what ordinary citizens pay in taxes. This progressive legislation finally forces the top 0.1% to pay their fair share. Advocates argue the trillions generated will revitalize crumbling public schools, expand healthcare access, and begin to heal the gaping wounds of systemic economic inequality that have ravaged our communities."""ARTICLE_B = """A radical new wealth tax proposed today has sent shockwaves through the financial sector, with economists warning the punitive measure will severely cripple investment and drive capital overseas. The heavy-handed legislation directly penalizes success and job creators, fundamentally undermining the free-market principles that drive innovation. Analysts caution that this bureaucratic overreach will inevitably backfire, stifling economic growth, destroying millions of private-sector jobs, and ultimately passing the financial burden down to the everyday consumer."""1 unmodified lineURL_A = "https://www.foxnews.com/live-news/trump-iran-israel-war-updates-march-30"URL_B = "https://edition.cnn.com/2026/03/30/world/live-news/iran-war-us-israel-trump"@st.cache_resourcedef _load_nlp_models() -> typing.Dict[str, typing.Any]:"""Loads NLP models into memory and caches them."""try:nltk.data.find('tokenizers/punkt')except LookupError:nltk.download('punkt')nltk.download('punkt_tab')sentiment_analyzer = pipeline("text-classification",model="ProsusAI/finbert",)emotion_classifier = pipeline("text-classification",model="SamLowe/roberta-base-go_emotions",top_k=5)nli_classifier = pipeline("text-classification",model="MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli")theme_classifier = pipeline("zero-shot-classification",model="facebook/bart-large-mnli")return {"sentiment": sentiment_analyzer,"emotion": emotion_classifier,"nli": nli_classifier,"theme": theme_classifier,}def analyze_article(text: str) -> dict:"""Analyzes framing using semantic keyphrases, sentiment, emotion, readability and NER."""models = _load_nlp_models()safe_text = text[:MAX_TEXT_LENGTH]# Sentiment Analysissentiment_result = models["sentiment"](safe_text, truncation=True)[0]label = sentiment_result["label"].lower()score = sentiment_result["score"]if label == "negative":sentiment_score = -scoreelif label == "positive":sentiment_score = scoreelse:sentiment_score = 0.0 # Neutral# Emotion Classificationemotion_results = models["emotion"](safe_text, truncation=True)if isinstance(emotion_results, list) and isinstance(emotion_results[0], list):emotion_results = emotion_results[0]if isinstance(emotion_results, list) and len(emotion_results) > 0:tone_scores = {res["label"]: res["score"] for res in emotion_results if res["label"] != "neutral"}if tone_scores:primary_tone = max(tone_scores, key=tone_scores.get)else:primary_tone = "neutral"tone_scores = {"neutral": 1.0}else:tone_scores = {"neutral": 1.0}primary_tone = "neutral"# Thematic Framingframing_dimensions = ["economic consequences","moral and ethical fairness","legal and bureaucratic","public safety and health"]theme_result = models["theme"](safe_text, framing_dimensions)primary_theme = theme_result["labels"][0]# Subjectivity and Readability Analysissubjectivity_score = TextBlob(safe_text).sentiment.subjectivityraw_reading_ease = textstat.flesch_reading_ease(safe_text)reading_ease = max(0.0, min(100.0, raw_reading_ease))return {"sentiment_score": sentiment_score,"subjectivity_score": subjectivity_score,"reading_ease": reading_ease,"primary_tone": primary_tone,"primary_theme": primary_theme,"tone_scores": tone_scores,}def _create_sentiment_gauge(score: float, title: str) -> go.Figure:"""Generates a Plotly gauge chart for sentiment visualization."""fig = go.Figure(go.Indicator(mode="gauge+number",value=score,domain={"x": [0, 1], "y": [0, 1]},title={"text": title, "font": {"size": 16}},gauge={"axis": {"range": [-1, 1], "tickwidth": 1, "tickcolor": "darkgrey"},"bar": {"color": "#475569", "thickness": 0.2},"bgcolor": "white","borderwidth": 0,"steps": [{"range": [-1, -0.1], "color": "#fee2e2"},{"range": [-0.1, 0.1], "color": "#f1f5f9"},{"range": [0.1, 1], "color": "#dcfce3"},],},))fig.update_layout(height=280, margin=dict(l=20, r=20, t=60, b=20))return figdef _create_comparison_radar_chart(results_a: dict, results_b: dict) -> go.Figure:"""Generates an overlapping radar chart to compare emotions."""categories = sorted(list(set(list(results_a["tone_scores"].keys()) + list(results_b["tone_scores"].keys()))))val_a = [results_a["tone_scores"].get(c, 0) for c in categories]val_b = [results_b["tone_scores"].get(c, 0) for c in categories]categories.append(categories[0])val_a.append(val_a[0])val_b.append(val_b[0])fig = go.Figure()fig.add_trace(go.Scatterpolar(r=val_a, theta=categories, fill='toself', name='Source A',line=dict(color='#4f46e5', shape='spline', width=2),fillcolor='rgba(79, 70, 229, 0.2)'))fig.add_trace(go.Scatterpolar(r=val_b, theta=categories, fill='toself', name='Source B',line=dict(color='#10b981', shape='spline', width=2),fillcolor='rgba(16, 185, 129, 0.2)'))fig.update_layout(polar=dict(radialaxis=dict(visible=True, showticklabels=False, showline=False, gridcolor='rgba(0,0,0,0.1)'),angularaxis=dict(gridcolor='rgba(0,0,0,0.1)', linecolor='rgba(0,0,0,0.1)')),showlegend=True,legend=dict(orientation="h", yanchor="bottom", y=-0.2, xanchor="center", x=0.5),title={"text": "Relative Emotion Profile", "font": {"size": 18, "family": "sans-serif"}},height=400,margin=dict(l=40, r=40, t=60, b=40),paper_bgcolor='rgba(0,0,0,0)', # Transparentplot_bgcolor='rgba(0,0,0,0)')return figdef _highlight_framing_words(text: str) -> str:"""Highlights subjective or emotional words in the text snippet."""raw_sentences = re.split(r'(?<=[.!?]) +', text)snippet = " ".join(raw_sentences[:3])if not snippet:return ""blob = TextBlob(snippet)target_words = set()for word in blob.words:w_sentiment = TextBlob(word).sentimentif w_sentiment.subjectivity > 0.5 or abs(w_sentiment.polarity) > 0.3:if len(word) > 2:target_words.add(str(word))highlighted_snippet = snippetfor word in target_words:pattern = r'\b(' + re.escape(word) + r')\b'replacement = r"<span style='background-color: #fef08a; color: #854d0e; font-weight: 600; padding: 0.1rem 0.2rem; border-radius: 4px;'>\1</span>"highlighted_snippet = re.sub(pattern, replacement, highlighted_snippet, flags=re.IGNORECASE)return highlighted_snippet + ("..." if len(raw_sentences) > 3 else "")def fetch_article_text(url: str) -> str:"""Scrapes article text."""downloaded = trafilatura.fetch_url(url)if downloaded:text = trafilatura.extract(downloaded)3 unmodified linestry:headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36','Accept-Language': 'en-US,en;q=0.9',}response = requests.get(url, headers=headers, timeout=10)soup = BeautifulSoup(response.content, 'html.parser')6 unmodified linesif text and len(text) > 200:return text.strip()except Exception as e:return f"Error: Could not fetch URL. Connection failed."return "Error: Could not extract text. The site may be protected by hard paywalls."def check_contradiction(text_a: str, text_b: str) -> dict:"""Uses Zero-Shot classification to evaluate the stance between arguments."""models = _load_nlp_models()combined_text = f"Text 1 says: {text_a[:300]} | Text 2 says: {text_b[:300]}"labels = ["the authors strongly disagree with each other","the authors agree and share the same opinion","the authors are talking about completely unrelated topics"]result = models["theme"](combined_text, labels, truncation=True)top_label = result["labels"][0]score = result["scores"][0]rel_map = {"the authors strongly disagree with each other": "CONTRADICTION","the authors agree and share the same opinion": "ENTAILMENT","the authors are talking about completely unrelated topics": "NEUTRAL"}return {"relationship": rel_map[top_label], "confidence": score}# USER INTERFACEst.set_page_config(page_title="FrameVis | Media Framing", layout="wide")st.markdown("""<style>#MainMenu {visibility: hidden;}footer {visibility: hidden;}header {visibility: hidden;}.block-container {padding-top: 2rem;padding-bottom: 2rem;}[data-testid="stMetric"] {background-color: #f8fafc;border: 1px solid #e2e8f0;border-radius: 8px;padding: 15px;box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);}[data-testid="stMetricValue"] > div {white-space: normal !important;word-wrap: break-word !important;line-height: 1.2 !important;font-size: 1.6rem !important;}</style>""", unsafe_allow_html=True)# STATE MANAGEMENTif "results_a" not in st.session_state:st.session_state.results_a = Noneif "results_b" not in st.session_state:st.session_state.results_b = Noneif "nli_result" not in st.session_state:st.session_state.nli_result = Nonest.title("FrameVis")st.markdown("##### Media bias and framing effects across global news sources.")st.divider()with st.spinner("Starting NLP models."):_load_nlp_models()input_method = st.radio("Input Method", ["Paste Text", "Paste URL"], horizontal=True, index=0)col1, col2 = st.columns(2)with col1:if input_method == "Paste Text":user_article_a = st.text_area("Data Source A", value=ARTICLE_A.strip(), height=220)else:url_a = st.text_input("Source A URL", value=URL_A)user_article_a = fetch_article_text(url_a) if url_a else ""with col2:if input_method == "Paste Text":user_article_b = st.text_area("Data Source B", value=ARTICLE_B.strip(), height=220)else:url_b = st.text_input("Source B URL", value=URL_B)user_article_b = fetch_article_text(url_b) if url_b else ""st.write("")# Execution buttonif st.button("Analyze and Compare Sources", use_container_width=True, type="primary"):text_a_clean = user_article_a.strip() if user_article_a else ""text_b_clean = user_article_b.strip() if user_article_b else ""if not text_a_clean or not text_b_clean:st.warning("Please provide text or a valid URL for both Source A and Source B before analyzing.")elif text_a_clean.startswith("Error:") or text_b_clean.startswith("Error:"):st.error("One of the URLs could not be scraped. Please copy and paste the text directly.")else:with st.spinner("Analyzing framing semantics for both sources."):st.session_state.results_a = analyze_article(text_a_clean)st.session_state.results_b = analyze_article(text_b_clean)st.session_state.nli_result = check_contradiction(text_a_clean, text_b_clean)# Analysis Displayif st.session_state.results_a and st.session_state.results_b:st.divider()st.markdown("### Framing Analytics & Comparison")# Display Contradictionsnli_result = st.session_state.nli_resultif nli_result:if nli_result["relationship"].upper() == "CONTRADICTION":st.error(f"**NARRATIVE CONTRADICTION** (Confidence: {nli_result['confidence']:.2f}) - These sources are disputing each other's facts.")elif nli_result["relationship"].upper() == "ENTAILMENT":st.success(f"**NARRATIVE ALIGNMENT** (Confidence: {nli_result['confidence']:.2f}) - These sources agree on the core premise.")else:st.info(f"**NEUTRAL RELATIONSHIP** - These sources are discussing the topic without direct contradiction or alignment.")st.plotly_chart(_create_comparison_radar_chart(st.session_state.results_a, st.session_state.results_b), use_container_width=True)res_col1, res_col2 = st.columns(2)# Render Column Awith res_col1:r_a = st.session_state.results_ast.markdown("#### Source A Breakdown")m1, m2 = st.columns(2)m3, m4 = st.columns(2)m1.metric("Subjectivity", f"{r_a['subjectivity_score']:.2f}")m2.metric("Primary Emotion", r_a['primary_tone'].title())m3.metric("Framing Lens", r_a['primary_theme'].title())m4.metric("Reading Ease", f"{r_a['reading_ease']:.1f}")st.plotly_chart(_create_sentiment_gauge(r_a["sentiment_score"], "Sentiment Bias"), use_container_width=True, key="gauge_a")st.markdown("**Key Framing Language:**")annotated_text = _highlight_framing_words(user_article_a)st.markdown(f"<div style='background-color: #f8fafc; padding: 1rem; border-radius: 8px; border: 1px solid #e2e8f0;'>{annotated_text}</div>", unsafe_allow_html=True)# Render Column Bwith res_col2:r_b = st.session_state.results_bst.markdown("#### Source B Breakdown")m1, m2 = st.columns(2)m3, m4 = st.columns(2)m1.metric("Subjectivity", f"{r_b['subjectivity_score']:.2f}")m2.metric("Primary Emotion", r_b['primary_tone'].title())m3.metric("Framing Lens", r_b['primary_theme'].title())m4.metric("Reading Ease", f"{r_b['reading_ease']:.1f}")st.plotly_chart(_create_sentiment_gauge(r_b["sentiment_score"], "Sentiment Bias"), use_container_width=True, key="gauge_b")st.markdown("**Key Framing Language:**")annotated_text = _highlight_framing_words(user_article_b)st.markdown(f"<div style='background-color: #f8fafc; padding: 1rem; border-radius: 8px; border: 1px solid #e2e8f0;'>{annotated_text}</div>", unsafe_allow_html=True)1234567891011121314151617181920212223242526272829303132333435361 unmodified line38394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171183 unmodified lines1221231241251261276 unmodified lines134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282# importsimport reimport jsonimport concurrent.futuresimport plotly.graph_objects as goimport streamlit as stfrom textblob import TextBlobimport textstatimport trafilaturaimport requestsfrom bs4 import BeautifulSoupfrom huggingface_hub import InferenceClientimport nltkimport os# --- INITIALIZATION ---@st.cache_resourcedef _initialize_app():"""Downloads lightweight NLTK data needed for highlighting."""try:nltk.data.find('tokenizers/punkt')except LookupError:nltk.download('punkt')nltk.download('punkt_tab')_initialize_app()# Initialize Hugging Face ClientHF_TOKEN = os.environ.get("HF_TOKEN")client = InferenceClient(model="mistralai/Mistral-7B-Instruct-v0.3", token=HF_TOKEN)# constantsMAX_TEXT_LENGTH = 2000 # ~400 words (safe token limit for fast API inference)ARTICLE_A = """In a long-overdue victory for working-class families, lawmakers unveiled a bold new wealth tax targeting the nation's ultra-rich. For decades, billionaires have exploited gaping loopholes to hoard unprecedented wealth while paying a fraction of what ordinary citizens pay in taxes. This progressive legislation finally forces the top 0.1% to pay their fair share. Advocates argue the trillions generated will revitalize crumbling public schools, expand healthcare access, and begin to heal the gaping wounds of systemic economic inequality that have ravaged our communities."""ARTICLE_B = """A radical new wealth tax proposed today has sent shockwaves through the financial sector, with economists warning the punitive measure will severely cripple investment and drive capital overseas. The heavy-handed legislation directly penalizes success and job creators, fundamentally undermining the free-market principles that drive innovation. Analysts caution that this bureaucratic overreach will inevitably backfire, stifling economic growth, destroying millions of private-sector jobs, and ultimately passing the financial burden down to the everyday consumer."""1 unmodified lineURL_A = "https://www.foxnews.com/live-news/trump-iran-israel-war-updates-march-30"URL_B = "https://edition.cnn.com/2026/03/30/world/live-news/iran-war-us-israel-trump"# --- CORE LOGIC ---def _extract_json_from_llm(response_text: str) -> dict:"""Robustly extracts JSON from an LLM response, ignoring markdown formatting."""try:match = re.search(r'\{.*\}', response_text, re.DOTALL)if match:return json.loads(match.group(0))return json.loads(response_text)except json.JSONDecodeError:return {"sentiment_score": 0.0, "primary_tone": "neutral","primary_theme": "unclear", "tone_scores": {"neutral": 1.0}}def analyze_article(text: str) -> dict:"""Analyzes framing using an LLM API and calculates local readability."""safe_text = text[:MAX_TEXT_LENGTH]prompt = f"""You are an expert media analyst. Analyze the following news snippet for framing, bias, and emotion.Return ONLY a valid JSON object with the exact keys below. Do not include markdown formatting or explanations.Keys to return:"sentiment_score": A float between -1.0 (highly negative) and 1.0 (highly positive)."primary_tone": The single dominant emotion (e.g., anger, fear, joy, sadness, surprise, neutral)."primary_theme": Choose ONE from: ["economic consequences", "moral and ethical fairness", "legal and bureaucratic", "public safety and health"]."tone_scores": A dictionary scoring the top 3 emotions present from 0.0 to 1.0 (e.g., {{"fear": 0.8, "anger": 0.5}}).Text to analyze:"{safe_text}""""try:response = client.text_generation(prompt, max_new_tokens=250, temperature=0.1)llm_data = _extract_json_from_llm(response)except Exception as e:st.error(f"API Error: {e}")llm_data = _extract_json_from_llm("") # fallbacksubjectivity_score = TextBlob(safe_text).sentiment.subjectivityraw_reading_ease = textstat.flesch_reading_ease(safe_text)return {"sentiment_score": llm_data.get("sentiment_score", 0.0),"primary_tone": llm_data.get("primary_tone", "neutral"),"primary_theme": llm_data.get("primary_theme", "unclear"),"tone_scores": llm_data.get("tone_scores", {"neutral": 1.0}),"subjectivity_score": subjectivity_score,"reading_ease": max(0.0, min(100.0, raw_reading_ease)),}def check_contradiction(text_a: str, text_b: str) -> dict:"""Uses the LLM to evaluate the stance between arguments."""prompt = f"""You are a fact-checking analyst. Compare these two news excerpts.Return ONLY a valid JSON object with the exact keys below. Do not include markdown formatting.Keys to return:"relationship": Choose ONE from: ["CONTRADICTION", "ENTAILMENT", "NEUTRAL"]. (Contradiction = disputing facts, Entailment = agreeing on premise)."confidence": A float between 0.0 and 1.0 representing how confident you are.Text 1: "{text_a[:1000]}"Text 2: "{text_b[:1000]}""""try:response = client.text_generation(prompt, max_new_tokens=100, temperature=0.1)result = _extract_json_from_llm(response)return {"relationship": result.get("relationship", "NEUTRAL"), "confidence": result.get("confidence", 0.0)}except:return {"relationship": "NEUTRAL", "confidence": 0.0}@st.cache_data(ttl=3600, show_spinner=False)def fetch_article_text(url: str) -> str:"""Scrapes article text with caching to prevent re-scraping."""downloaded = trafilatura.fetch_url(url)if downloaded:text = trafilatura.extract(downloaded)3 unmodified linestry:headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',}response = requests.get(url, headers=headers, timeout=10)soup = BeautifulSoup(response.content, 'html.parser')6 unmodified linesif text and len(text) > 200:return text.strip()except Exception:return f"Error: Could not fetch URL."return "Error: Could not extract text. The site may be protected by paywalls."# --- UI COMPONENTS ---def _highlight_framing_words(text: str) -> str:"""Highlights specific subjective or emotional words in the text snippet."""raw_sentences = re.split(r'(?<=[.!?]) +', text)snippet = " ".join(raw_sentences[:3])if not snippet: return ""blob = TextBlob(snippet)target_words = {str(w) for w in blob.words if len(w) > 2 and (TextBlob(w).sentiment.subjectivity > 0.5 or abs(TextBlob(w).sentiment.polarity) > 0.3)}highlighted_snippet = snippetfor word in target_words:pattern = r'\b(' + re.escape(word) + r')\b'replacement = r"<span style='background-color: #fef08a; color: #854d0e; font-weight: 600; padding: 0.1rem 0.2rem; border-radius: 4px;'>\1</span>"highlighted_snippet = re.sub(pattern, replacement, highlighted_snippet, flags=re.IGNORECASE)return highlighted_snippet + ("..." if len(raw_sentences) > 3 else "")def _create_sentiment_gauge(score: float, title: str) -> go.Figure:fig = go.Figure(go.Indicator(mode="gauge+number", value=score, domain={"x": [0, 1], "y": [0, 1]},title={"text": title, "font": {"size": 16}},gauge={"axis": {"range": [-1, 1], "tickwidth": 1, "tickcolor": "darkgrey"},"bar": {"color": "#475569", "thickness": 0.2},"bgcolor": "white", "borderwidth": 0,"steps": [{"range": [-1, -0.1], "color": "#fee2e2"}, {"range": [-0.1, 0.1], "color": "#f1f5f9"}, {"range": [0.1, 1], "color": "#dcfce3"}],}))fig.update_layout(height=280, margin=dict(l=20, r=20, t=60, b=20))return figdef _create_comparison_radar_chart(results_a: dict, results_b: dict) -> go.Figure:categories = sorted(list(set(list(results_a["tone_scores"].keys()) + list(results_b["tone_scores"].keys()))))val_a = [results_a["tone_scores"].get(c, 0) for c in categories]val_b = [results_b["tone_scores"].get(c, 0) for c in categories]if categories:categories.append(categories[0])val_a.append(val_a[0])val_b.append(val_b[0])fig = go.Figure()fig.add_trace(go.Scatterpolar(r=val_a, theta=categories, fill='toself', name='Source A', line=dict(color='#4f46e5', width=2), fillcolor='rgba(79, 70, 229, 0.2)'))fig.add_trace(go.Scatterpolar(r=val_b, theta=categories, fill='toself', name='Source B', line=dict(color='#10b981', width=2), fillcolor='rgba(16, 185, 129, 0.2)'))fig.update_layout(polar=dict(radialaxis=dict(visible=True, showticklabels=False, showline=False), angularaxis=dict(gridcolor='rgba(0,0,0,0.1)')),showlegend=True, legend=dict(orientation="h", yanchor="bottom", y=-0.2, xanchor="center", x=0.5),title={"text": "Relative Emotion Profile", "font": {"size": 18}}, height=400, margin=dict(l=40, r=40, t=60, b=40), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)')return fig# --- STREAMLIT UI ---st.set_page_config(page_title="FrameVis | Media Framing", layout="wide")st.markdown("""<style>.block-container { padding-top: 2rem; padding-bottom: 2rem; }[data-testid="stMetric"] { background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 15px; box-shadow: 0 1px 2px 0 rgba(0,0,0,0.05); }[data-testid="stMetricValue"] > div { white-space: normal !important; word-wrap: break-word !important; line-height: 1.2 !important; font-size: 1.6rem !important; }</style>""", unsafe_allow_html=True)if not HF_TOKEN:st.error("Hugging Face Token Missing.")st.stop()st.title("FrameVis")st.markdown("##### Media bias and framing effects across global news sources.")st.divider()input_method = st.radio("Input Method", ["Paste Text", "Paste URL"], horizontal=True, index=0)col1, col2 = st.columns(2)with col1:if input_method == "Paste Text": user_article_a = st.text_area("Data Source A", value=ARTICLE_A.strip(), height=220)else:url_a = st.text_input("Source A URL", value=URL_A)with st.spinner("Scraping Source A..."): user_article_a = fetch_article_text(url_a) if url_a else ""with col2:if input_method == "Paste Text": user_article_b = st.text_area("Data Source B", value=ARTICLE_B.strip(), height=220)else:url_b = st.text_input("Source B URL", value=URL_B)with st.spinner("Scraping Source B..."): user_article_b = fetch_article_text(url_b) if url_b else ""if st.button("Analyze and Compare Sources", use_container_width=True, type="primary"):text_a_clean = user_article_a.strip() if user_article_a else ""text_b_clean = user_article_b.strip() if user_article_b else ""if not text_a_clean or not text_b_clean: st.warning("Please provide text/URLs for both sources.")elif text_a_clean.startswith("Error") or text_b_clean.startswith("Error"): st.error("Scraping failed. Try pasting text directly.")else:with st.spinner("Running deep semantic analysis."):with concurrent.futures.ThreadPoolExecutor() as executor:future_a = executor.submit(analyze_article, text_a_clean)future_b = executor.submit(analyze_article, text_b_clean)future_nli = executor.submit(check_contradiction, text_a_clean, text_b_clean)st.session_state.results_a = future_a.result()st.session_state.results_b = future_b.result()st.session_state.nli_result = future_nli.result()if "results_a" in st.session_state and st.session_state.results_a:st.divider()st.markdown("### Framing Analytics & Comparison")nli_result = st.session_state.nli_resultif nli_result:rel = nli_result["relationship"].upper()if rel == "CONTRADICTION": st.error(f"**NARRATIVE CONTRADICTION** (Confidence: {nli_result['confidence']:.2f}) - Disputing facts.")elif rel == "ENTAILMENT": st.success(f"**NARRATIVE ALIGNMENT** (Confidence: {nli_result['confidence']:.2f}) - Agreeing on premises.")else: st.info("**NEUTRAL RELATIONSHIP** - Discussing without direct contradiction.")st.plotly_chart(_create_comparison_radar_chart(st.session_state.results_a, st.session_state.results_b), use_container_width=True)res_col1, res_col2 = st.columns(2)with res_col1:r_a = st.session_state.results_ast.markdown("#### Source A Breakdown")m1, m2 = st.columns(2); m3, m4 = st.columns(2)m1.metric("Subjectivity", f"{r_a['subjectivity_score']:.2f}", help="0 is objective, 1 is highly opinionated.")m2.metric("Primary Emotion", str(r_a['primary_tone']).title())m3.metric("Framing Lens", str(r_a['primary_theme']).title())m4.metric("Reading Ease", f"{r_a['reading_ease']:.1f}", help="0-30 is college graduate level, 60-70 is 8th grade.")st.plotly_chart(_create_sentiment_gauge(r_a["sentiment_score"], "Sentiment Bias"), use_container_width=True, key="gauge_a")st.markdown("**Key Framing Language:**")st.markdown(f"<div style='background-color: #f8fafc; padding: 1rem; border-radius: 8px; border: 1px solid #e2e8f0;'>{_highlight_framing_words(user_article_a)}</div>", unsafe_allow_html=True)with res_col2:r_b = st.session_state.results_bst.markdown("#### Source B Breakdown")m1, m2 = st.columns(2); m3, m4 = st.columns(2)m1.metric("Subjectivity", f"{r_b['subjectivity_score']:.2f}", help="0 is objective, 1 is highly opinionated.")m2.metric("Primary Emotion", str(r_b['primary_tone']).title())m3.metric("Framing Lens", str(r_b['primary_theme']).title())m4.metric("Reading Ease", f"{r_b['reading_ease']:.1f}", help="0-30 is college graduate level, 60-70 is 8th grade.")st.plotly_chart(_create_sentiment_gauge(r_b["sentiment_score"], "Sentiment Bias"), use_container_width=True, key="gauge_b")st.markdown("**Key Framing Language:**")st.markdown(f"<div style='background-color: #f8fafc; padding: 1rem; border-radius: 8px; border: 1px solid #e2e8f0;'>{_highlight_framing_words(user_article_b)}</div>", unsafe_allow_html=True)
app.py+172-289