Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -129,6 +129,134 @@
|
|
| 129 |
# # st.subheader(" RAG-Generated Summary")
|
| 130 |
# # summary = rag_summarize(collected, summarizer)
|
| 131 |
# # st.success(summary)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
import streamlit as st
|
| 134 |
import pandas as pd
|
|
@@ -139,7 +267,7 @@ from sklearn.metrics.pairwise import cosine_similarity
|
|
| 139 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 140 |
from datetime import datetime
|
| 141 |
|
| 142 |
-
#
|
| 143 |
@st.cache_data
|
| 144 |
def load_data():
|
| 145 |
df = pd.read_csv("Illinois_Entire_Data_Insights_Final_v2.csv")
|
|
@@ -150,22 +278,25 @@ def load_data():
|
|
| 150 |
df["summary_insight"] = df["llama_trend_summary"] + "\n" + df["llama_insight"]
|
| 151 |
return df
|
| 152 |
|
|
|
|
| 153 |
@st.cache_resource
|
| 154 |
def load_models():
|
| 155 |
embed_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 156 |
summarizer = pipeline("summarization", model="t5-small", tokenizer="t5-small")
|
| 157 |
return embed_model, summarizer
|
| 158 |
|
|
|
|
| 159 |
@st.cache_data
|
| 160 |
def compute_embeddings(texts, _model):
|
| 161 |
return _model.encode(texts, show_progress_bar=True)
|
| 162 |
|
| 163 |
-
|
|
|
|
| 164 |
query_embedding = model.encode([query])
|
| 165 |
sims = cosine_similarity(query_embedding, embeddings)[0]
|
| 166 |
return [(i, s) for i, s in enumerate(sims) if s > threshold]
|
| 167 |
|
| 168 |
-
|
| 169 |
def rag_summarize(texts, summarizer, top_k=5):
|
| 170 |
if not texts:
|
| 171 |
return "No relevant content to summarize."
|
|
@@ -179,6 +310,7 @@ def rag_summarize(texts, summarizer, top_k=5):
|
|
| 179 |
out = summarizer(prompt, max_length=60, min_length=30, do_sample=False)
|
| 180 |
return out[0]['summary_text']
|
| 181 |
|
|
|
|
| 182 |
def extract_month_year(q):
|
| 183 |
month_map = {m: i for i, m in enumerate(
|
| 184 |
["january", "february", "march", "april", "may", "june",
|
|
@@ -189,6 +321,7 @@ def extract_month_year(q):
|
|
| 189 |
yr = int(ym.group()) if ym else None
|
| 190 |
return mon, yr
|
| 191 |
|
|
|
|
| 192 |
def extract_topic_match(query, df):
|
| 193 |
query_lower = query.lower()
|
| 194 |
matched_rows = df[
|
|
@@ -199,14 +332,16 @@ def extract_topic_match(query, df):
|
|
| 199 |
]
|
| 200 |
return matched_rows
|
| 201 |
|
| 202 |
-
|
| 203 |
st.set_page_config(page_title="IL Trends Q&A", layout="wide")
|
| 204 |
st.title("Illinois Legislative Trends Q&A")
|
| 205 |
-
st.markdown("Ask about trends in **topics** like education, higher education, etc
|
| 206 |
|
|
|
|
| 207 |
df = load_data()
|
| 208 |
embed_model, summarizer = load_models()
|
| 209 |
|
|
|
|
| 210 |
query = st.text_input(" Ask a question (e.g., ‘trends in Higher education in 2024’):")
|
| 211 |
|
| 212 |
if query:
|
|
@@ -214,7 +349,8 @@ if query:
|
|
| 214 |
df2 = extract_topic_match(query, df)
|
| 215 |
|
| 216 |
if df2.empty:
|
| 217 |
-
df2 = df
|
|
|
|
| 218 |
if yr:
|
| 219 |
df2 = df2[df2['status_date'].dt.year == yr]
|
| 220 |
if mon:
|
|
@@ -233,7 +369,7 @@ if query:
|
|
| 233 |
if not res:
|
| 234 |
st.warning("No relevant insights found.")
|
| 235 |
else:
|
| 236 |
-
st.subheader(" Top Matching Insights")
|
| 237 |
collected = []
|
| 238 |
|
| 239 |
for idx, score in sorted(res, key=lambda x: x[1], reverse=True)[:5]:
|
|
@@ -244,15 +380,19 @@ if query:
|
|
| 244 |
intent = row['intent_standardized']
|
| 245 |
stance = row['stance_standardized']
|
| 246 |
trend_summary = row['llama_trend_summary'].strip()
|
|
|
|
|
|
|
| 247 |
|
| 248 |
-
st.markdown(f"-
|
| 249 |
-
st.markdown(f"
|
| 250 |
-
st.markdown(f"
|
| 251 |
-
st.markdown(f"
|
| 252 |
-
st.markdown(f"
|
|
|
|
|
|
|
| 253 |
|
| 254 |
collected.append(row['summary_insight'])
|
| 255 |
|
| 256 |
-
st.subheader(" RAG-Generated Summary")
|
| 257 |
summary = rag_summarize(collected, summarizer)
|
| 258 |
st.success(summary)
|
|
|
|
| 129 |
# # st.subheader(" RAG-Generated Summary")
|
| 130 |
# # summary = rag_summarize(collected, summarizer)
|
| 131 |
# # st.success(summary)
|
| 132 |
+
# use the below one
|
| 133 |
+
# import streamlit as st
|
| 134 |
+
# import pandas as pd
|
| 135 |
+
# import re
|
| 136 |
+
# from sentence_transformers import SentenceTransformer
|
| 137 |
+
# from transformers import pipeline
|
| 138 |
+
# from sklearn.metrics.pairwise import cosine_similarity
|
| 139 |
+
# from sklearn.feature_extraction.text import TfidfVectorizer
|
| 140 |
+
# from datetime import datetime
|
| 141 |
+
|
| 142 |
+
# # loading data
|
| 143 |
+
# @st.cache_data
|
| 144 |
+
# def load_data():
|
| 145 |
+
# df = pd.read_csv("Illinois_Entire_Data_Insights_Final_v2.csv")
|
| 146 |
+
# df['status_date'] = pd.to_datetime(df['status_date'], format='%d-%m-%Y', errors='coerce')
|
| 147 |
+
# df = df.dropna(subset=['status_date'])
|
| 148 |
+
# df["llama_trend_summary"] = df["llama_trend_summary"].fillna("")
|
| 149 |
+
# df["llama_insight"] = df["llama_insight"].fillna("")
|
| 150 |
+
# df["summary_insight"] = df["llama_trend_summary"] + "\n" + df["llama_insight"]
|
| 151 |
+
# return df
|
| 152 |
+
|
| 153 |
+
# @st.cache_resource
|
| 154 |
+
# def load_models():
|
| 155 |
+
# embed_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 156 |
+
# summarizer = pipeline("summarization", model="t5-small", tokenizer="t5-small")
|
| 157 |
+
# return embed_model, summarizer
|
| 158 |
+
|
| 159 |
+
# @st.cache_data
|
| 160 |
+
# def compute_embeddings(texts, _model):
|
| 161 |
+
# return _model.encode(texts, show_progress_bar=True)
|
| 162 |
+
|
| 163 |
+
# def semantic_search(query, embeddings, model, threshold=0.5):
|
| 164 |
+
# query_embedding = model.encode([query])
|
| 165 |
+
# sims = cosine_similarity(query_embedding, embeddings)[0]
|
| 166 |
+
# return [(i, s) for i, s in enumerate(sims) if s > threshold]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# def rag_summarize(texts, summarizer, top_k=5):
|
| 170 |
+
# if not texts:
|
| 171 |
+
# return "No relevant content to summarize."
|
| 172 |
+
# vect = TfidfVectorizer()
|
| 173 |
+
# m = vect.fit_transform(texts)
|
| 174 |
+
# mean_vec = m.mean(axis=0).A
|
| 175 |
+
# scores = cosine_similarity(mean_vec, m).flatten()
|
| 176 |
+
# top_indices = scores.argsort()[::-1][:top_k]
|
| 177 |
+
# ctx = "\n".join(texts[i] for i in top_indices)
|
| 178 |
+
# prompt = "summarize: " + ctx[:1024]
|
| 179 |
+
# out = summarizer(prompt, max_length=60, min_length=30, do_sample=False)
|
| 180 |
+
# return out[0]['summary_text']
|
| 181 |
+
|
| 182 |
+
# def extract_month_year(q):
|
| 183 |
+
# month_map = {m: i for i, m in enumerate(
|
| 184 |
+
# ["january", "february", "march", "april", "may", "june",
|
| 185 |
+
# "july", "august", "september", "october", "november", "december"], 1)}
|
| 186 |
+
# ql = q.lower()
|
| 187 |
+
# mon = next((v for k, v in month_map.items() if k in ql), None)
|
| 188 |
+
# ym = re.search(r"(19|20)\d{2}", q)
|
| 189 |
+
# yr = int(ym.group()) if ym else None
|
| 190 |
+
# return mon, yr
|
| 191 |
+
|
| 192 |
+
# def extract_topic_match(query, df):
|
| 193 |
+
# query_lower = query.lower()
|
| 194 |
+
# matched_rows = df[
|
| 195 |
+
# df['category_&_subcategory_standardized'].fillna('').str.lower().str.contains(query_lower) |
|
| 196 |
+
# df['intent_standardized'].fillna('').str.lower().str.contains(query_lower) |
|
| 197 |
+
# df['legislative_goal_standardized'].fillna('').str.lower().str.contains(query_lower) |
|
| 198 |
+
# df['policy_impact_areas_standardized'].fillna('').str.lower().str.contains(query_lower)
|
| 199 |
+
# ]
|
| 200 |
+
# return matched_rows
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# st.set_page_config(page_title="IL Trends Q&A", layout="wide")
|
| 204 |
+
# st.title("Illinois Legislative Trends Q&A")
|
| 205 |
+
# st.markdown("Ask about trends in **topics** like education, higher education, etc!")
|
| 206 |
+
|
| 207 |
+
# df = load_data()
|
| 208 |
+
# embed_model, summarizer = load_models()
|
| 209 |
+
|
| 210 |
+
# query = st.text_input(" Ask a question (e.g., ‘trends in Higher education in 2024’):")
|
| 211 |
+
|
| 212 |
+
# if query:
|
| 213 |
+
# mon, yr = extract_month_year(query)
|
| 214 |
+
# df2 = extract_topic_match(query, df)
|
| 215 |
+
|
| 216 |
+
# if df2.empty:
|
| 217 |
+
# df2 = df
|
| 218 |
+
# if yr:
|
| 219 |
+
# df2 = df2[df2['status_date'].dt.year == yr]
|
| 220 |
+
# if mon:
|
| 221 |
+
# df2 = df2[df2['status_date'].dt.month == mon]
|
| 222 |
+
# st.info(f"Filtering by date: **{datetime(yr, mon, 1):%B %Y}**")
|
| 223 |
+
# else:
|
| 224 |
+
# st.info(f"Filtering by year: **{yr}**")
|
| 225 |
+
|
| 226 |
+
# if df2.empty:
|
| 227 |
+
# st.warning("No matching records found.")
|
| 228 |
+
# else:
|
| 229 |
+
# texts = df2['summary_insight'].tolist()
|
| 230 |
+
# embs = compute_embeddings(texts, _model=embed_model)
|
| 231 |
+
# res = semantic_search(query, embs, embed_model)
|
| 232 |
+
|
| 233 |
+
# if not res:
|
| 234 |
+
# st.warning("No relevant insights found.")
|
| 235 |
+
# else:
|
| 236 |
+
# st.subheader(" Top Matching Insights")
|
| 237 |
+
# collected = []
|
| 238 |
+
|
| 239 |
+
# for idx, score in sorted(res, key=lambda x: x[1], reverse=True)[:5]:
|
| 240 |
+
# row = df2.iloc[idx]
|
| 241 |
+
# date = row['status_date'].date()
|
| 242 |
+
# cat_std = row['category_&_subcategory_standardized']
|
| 243 |
+
# goal = row['legislative_goal_standardized']
|
| 244 |
+
# intent = row['intent_standardized']
|
| 245 |
+
# stance = row['stance_standardized']
|
| 246 |
+
# trend_summary = row['llama_trend_summary'].strip()
|
| 247 |
+
|
| 248 |
+
# st.markdown(f"- Date: {date} | Score: {score:.2f}")
|
| 249 |
+
# st.markdown(f" - Category: {cat_std}")
|
| 250 |
+
# st.markdown(f" - Goal: {goal}")
|
| 251 |
+
# st.markdown(f" - Intent:{intent} | Stance: {stance}")
|
| 252 |
+
# st.markdown(f" > Trend Summary: {trend_summary}")
|
| 253 |
+
|
| 254 |
+
# collected.append(row['summary_insight'])
|
| 255 |
+
|
| 256 |
+
# st.subheader(" RAG-Generated Summary")
|
| 257 |
+
# summary = rag_summarize(collected, summarizer)
|
| 258 |
+
# st.success(summary)
|
| 259 |
+
|
| 260 |
|
| 261 |
import streamlit as st
|
| 262 |
import pandas as pd
|
|
|
|
| 267 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 268 |
from datetime import datetime
|
| 269 |
|
| 270 |
+
# Load the legislative dataset
|
| 271 |
@st.cache_data
|
| 272 |
def load_data():
|
| 273 |
df = pd.read_csv("Illinois_Entire_Data_Insights_Final_v2.csv")
|
|
|
|
| 278 |
df["summary_insight"] = df["llama_trend_summary"] + "\n" + df["llama_insight"]
|
| 279 |
return df
|
| 280 |
|
| 281 |
+
# Load embedding and summarization models
|
| 282 |
@st.cache_resource
|
| 283 |
def load_models():
|
| 284 |
embed_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 285 |
summarizer = pipeline("summarization", model="t5-small", tokenizer="t5-small")
|
| 286 |
return embed_model, summarizer
|
| 287 |
|
| 288 |
+
# Compute embeddings for given text corpus
|
| 289 |
@st.cache_data
|
| 290 |
def compute_embeddings(texts, _model):
|
| 291 |
return _model.encode(texts, show_progress_bar=True)
|
| 292 |
|
| 293 |
+
# Perform semantic search to find relevant text chunks
|
| 294 |
+
def semantic_search(query, embeddings, model, threshold=0.5):
|
| 295 |
query_embedding = model.encode([query])
|
| 296 |
sims = cosine_similarity(query_embedding, embeddings)[0]
|
| 297 |
return [(i, s) for i, s in enumerate(sims) if s > threshold]
|
| 298 |
|
| 299 |
+
# Use TF-IDF to extract and summarize top-k relevant sections
|
| 300 |
def rag_summarize(texts, summarizer, top_k=5):
|
| 301 |
if not texts:
|
| 302 |
return "No relevant content to summarize."
|
|
|
|
| 310 |
out = summarizer(prompt, max_length=60, min_length=30, do_sample=False)
|
| 311 |
return out[0]['summary_text']
|
| 312 |
|
| 313 |
+
# Extract month and year from query string
|
| 314 |
def extract_month_year(q):
|
| 315 |
month_map = {m: i for i, m in enumerate(
|
| 316 |
["january", "february", "march", "april", "may", "june",
|
|
|
|
| 321 |
yr = int(ym.group()) if ym else None
|
| 322 |
return mon, yr
|
| 323 |
|
| 324 |
+
# Extract matching rows based on topic keywords
|
| 325 |
def extract_topic_match(query, df):
|
| 326 |
query_lower = query.lower()
|
| 327 |
matched_rows = df[
|
|
|
|
| 332 |
]
|
| 333 |
return matched_rows
|
| 334 |
|
| 335 |
+
# Streamlit app UI
|
| 336 |
st.set_page_config(page_title="IL Trends Q&A", layout="wide")
|
| 337 |
st.title("Illinois Legislative Trends Q&A")
|
| 338 |
+
st.markdown("Ask about trends in **topics** like education, higher education, healthcare, etc.")
|
| 339 |
|
| 340 |
+
# Load data and models
|
| 341 |
df = load_data()
|
| 342 |
embed_model, summarizer = load_models()
|
| 343 |
|
| 344 |
+
# Query input box
|
| 345 |
query = st.text_input(" Ask a question (e.g., ‘trends in Higher education in 2024’):")
|
| 346 |
|
| 347 |
if query:
|
|
|
|
| 349 |
df2 = extract_topic_match(query, df)
|
| 350 |
|
| 351 |
if df2.empty:
|
| 352 |
+
df2 = df # fallback to full dataset if nothing matched
|
| 353 |
+
|
| 354 |
if yr:
|
| 355 |
df2 = df2[df2['status_date'].dt.year == yr]
|
| 356 |
if mon:
|
|
|
|
| 369 |
if not res:
|
| 370 |
st.warning("No relevant insights found.")
|
| 371 |
else:
|
| 372 |
+
st.subheader("🔎 Top Matching Insights")
|
| 373 |
collected = []
|
| 374 |
|
| 375 |
for idx, score in sorted(res, key=lambda x: x[1], reverse=True)[:5]:
|
|
|
|
| 380 |
intent = row['intent_standardized']
|
| 381 |
stance = row['stance_standardized']
|
| 382 |
trend_summary = row['llama_trend_summary'].strip()
|
| 383 |
+
bill_id = row['bill_id']
|
| 384 |
+
url = row['state_link']
|
| 385 |
|
| 386 |
+
st.markdown(f"---")
|
| 387 |
+
st.markdown(f"**📅 Date:** {date} | **📄 Bill ID:** `{bill_id}` | **Score:** {score:.2f}")
|
| 388 |
+
st.markdown(f"**Category:** {cat_std}")
|
| 389 |
+
st.markdown(f"**Goal:** {goal}")
|
| 390 |
+
st.markdown(f"**Intent:** {intent} | **Stance:** {stance}")
|
| 391 |
+
st.markdown(f"**Trend Summary:** {trend_summary}")
|
| 392 |
+
st.markdown(f"[🔗 View Full Bill]({url})")
|
| 393 |
|
| 394 |
collected.append(row['summary_insight'])
|
| 395 |
|
| 396 |
+
st.subheader("🧠 RAG-Generated Summary")
|
| 397 |
summary = rag_summarize(collected, summarizer)
|
| 398 |
st.success(summary)
|