Spaces:
Runtime error
Runtime error
Update app.py
Browse files56 unmodified lines575859606162636465666768697071724 unmodified lines7778798081828362 unmodified lines146147148149150151152153154155156157158159160161162163164165166167168169170171172173174176 unmodified lines35135235335435535635710 unmodified lines36836937037137256 unmodified linesKeys 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}""""messages = [{"role": "user", "content": prompt}]response = client.chat_completion(messages=messages, max_tokens=250, temperature=0.1)response_text = response.choices[0].message.contentllm_data = _extract_json_from_llm(response_text)4 unmodified lines"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)),}62 unmodified linesreturn 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 "")@st.cache_data(ttl=3600, show_spinner=False)def fetch_article_text(url: str) -> str:176 unmodified linesst.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 B10 unmodified linesst.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)56 unmodified lines57585960616263646566676869707172734 unmodified lines787980818283848562 unmodified lines148149150151152153154155156157158159160161162163164165166167168176 unmodified lines34534634734834935035110 unmodified lines36236336436536656 unmodified linesKeys to return:"sentiment_score": A float between -1.0 (highly negative) and 1.0 (highly positive)."primary_tone": The single dominant emotion."primary_theme": Choose ONE from: ["economic consequences", "moral and ethical fairness", "legal and bureaucratic", "public safety and health"]."tone_scores": A dictionary scoring THESE EXACT 6 EMOTIONS from 0.0 to 1.0: {{"anger": 0.0, "fear": 0.0, "joy": 0.0, "sadness": 0.0, "surprise": 0.0, "trust": 0.0}}."framing_words": A list of the 5 to 8 most emotionally charged, biased, or subjective words used in the text (e.g., ["draconian", "slammed", "titans", "catastrophic"]).Text to analyze:"{safe_text}""""messages = [{"role": "user", "content": prompt}]response = client.chat_completion(messages=messages, max_tokens=300, temperature=0.1)response_text = response.choices[0].message.contentllm_data = _extract_json_from_llm(response_text)4 unmodified lines"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", {"anger": 0, "fear": 0, "joy": 0, "sadness": 0, "surprise": 0, "trust": 0}),"framing_words": llm_data.get("framing_words", []),"subjectivity_score": subjectivity_score,"reading_ease": max(0.0, min(100.0, raw_reading_ease)),}62 unmodified linesreturn figdef _highlight_framing_words(text: str, target_words: list) -> str:"""Highlights LLM-identified framing words in the full text snippet."""if not text:return ""words = text.split()highlighted_text = display_textfor word in target_words:if len(word) > 2: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_text = re.sub(pattern, replacement, highlighted_text, flags=re.IGNORECASE)return highlighted_text@st.cache_data(ttl=3600, show_spinner=False)def fetch_article_text(url: str) -> str:176 unmodified linesst.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, r_a['framing_words'])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 B10 unmodified linesst.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, r_b['framing_words'])st.markdown(f"<div style='background-color: #f8fafc; padding: 1rem; border-radius: 8px; border: 1px solid #e2e8f0;'>{annotated_text}</div>", unsafe_allow_html=True)
app.py+18-24