Sandini commited on
Commit
b2c9005
·
verified ·
1 Parent(s): 7636d3b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -0
app.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from transformers import pipeline
4
+ from sklearn.metrics.pairwise import cosine_similarity
5
+ from sentence_transformers import SentenceTransformer
6
+ import string
7
+ from nltk.tokenize import word_tokenize
8
+ from nltk.corpus import stopwords
9
+ from nltk.stem import WordNetLemmatizer
10
+ import nltk
11
+
12
+ # Download NLTK resources (run this once if not already downloaded)
13
+ nltk.download('punkt')
14
+ nltk.download('punkt_tab')
15
+ nltk.download('stopwords')
16
+ nltk.download('wordnet')
17
+
18
+ # Set modern page configuration
19
+ st.set_page_config(page_title="News Analyzer", layout="wide")
20
+
21
+ # Inject custom CSS for sleek dark blue theme with black fonts
22
+ st.markdown("""
23
+ <style>
24
+ /* Global Styling */
25
+ body {
26
+ background: #0b132b;
27
+ font-family: 'Arial', sans-serif;
28
+ margin: 0;
29
+ padding: 0;
30
+ }
31
+
32
+ /* Header Styling */
33
+ .custom-header {
34
+ background: linear-gradient(to right, #1f4068, #1b1b2f);
35
+ padding: 1.5rem;
36
+ margin-bottom: 1.5rem;
37
+ border-radius: 12px;
38
+ text-align: center;
39
+ font-size: 30px;
40
+ font-weight: bold;
41
+ box-shadow: 0px 4px 15px rgba(0, 217, 255, 0.3);
42
+ }
43
+
44
+ /* Buttons */
45
+ .stButton>button {
46
+ background: linear-gradient(45deg, #0072ff, #00c6ff);
47
+ border-radius: 8px;
48
+ padding: 14px 28px;
49
+ font-size: 18px;
50
+ transition: 0.3s ease;
51
+ border: none;
52
+ }
53
+ .stButton>button:hover {
54
+ transform: scale(1.05);
55
+ box-shadow: 0px 4px 10px rgba(0, 255, 255, 0.5);
56
+ }
57
+
58
+ /* Text Input */
59
+ .stTextInput>div>div>input {
60
+ background-color: rgba(255, 255, 255, 0.1);
61
+ border-radius: 8px;
62
+ padding: 12px;
63
+ font-size: 18px;
64
+ }
65
+
66
+ /* Dataframe Container */
67
+ .dataframe-container {
68
+ background: rgba(255, 255, 255, 0.1);
69
+ padding: 15px;
70
+ border-radius: 12px;
71
+ }
72
+
73
+ /* Answer Display Box - Larger */
74
+ .answer-box {
75
+ background: rgba(0, 217, 255, 0.15);
76
+ padding: 35px;
77
+ border-radius: 15px;
78
+ border: 2px solid rgba(0, 217, 255, 0.6);
79
+ font-size: 22px;
80
+ text-align: center;
81
+ margin-bottom: 20px;
82
+ min-height: 150px;
83
+ box-shadow: 0px 2px 12px rgba(0, 217, 255, 0.3);
84
+ display: flex;
85
+ align-items: center;
86
+ justify-content: center;
87
+ transition: all 0.3s ease;
88
+ }
89
+
90
+ /* CSV Display Box */
91
+ .csv-box {
92
+ background: rgba(255, 255, 255, 0.1);
93
+ padding: 15px;
94
+ border-radius: 12px;
95
+ margin-top: 20px;
96
+ box-shadow: 0px 2px 12px rgba(0, 217, 255, 0.3);
97
+ }
98
+ </style>
99
+ """, unsafe_allow_html=True)
100
+
101
+ # Modern Header
102
+ st.markdown("<div class='custom-header'> 🧩 AI-Powered News Analyzer</div>", unsafe_allow_html=True)
103
+
104
+ # Load the Hugging Face models
105
+ classifier = pipeline("text-classification", model="Sandini/news-classifier") # Classification pipeline
106
+ qa_pipeline = pipeline("question-answering", model="distilbert/distilbert-base-cased-distilled-squad") # QA pipeline
107
+
108
+ # Initialize sentence transformer model for QA similarity
109
+ sentence_model = SentenceTransformer('all-MiniLM-L6-v2') # Pre-trained sentence model
110
+
111
+ # Define preprocessing functions for classification
112
+ def preprocess_text(text):
113
+ # Step 1: Lowercase the text
114
+ text = text.lower()
115
+
116
+ # Step 2: Remove punctuation
117
+ text = text.translate(str.maketrans('', '', string.punctuation))
118
+
119
+ # Step 3: Tokenize the text
120
+ tokens = word_tokenize(text)
121
+
122
+ # Step 4: Remove stopwords
123
+ stop_words = set(stopwords.words('english'))
124
+ tokens = [word for word in tokens if word not in stop_words]
125
+
126
+ # Step 5: Lemmatization
127
+ lemmatizer = WordNetLemmatizer()
128
+ tokens = [lemmatizer.lemmatize(word) for word in tokens]
129
+
130
+ # Step 6: Join tokens back into a single string
131
+ preprocessed_text = " ".join(tokens)
132
+
133
+ return preprocessed_text
134
+
135
+ # Reverse mapping (numeric label -> category name)
136
+ label_mapping = {
137
+ "Business": 0,
138
+ "Opinion": 1,
139
+ "Sports": 2,
140
+ "Political_gossip": 3,
141
+ "World_news": 4
142
+ }
143
+ reverse_label_mapping = {v: k for k, v in label_mapping.items()}
144
+
145
+ # Define a function to predict the category for a single text
146
+ def predict_category(text):
147
+ prediction = classifier(text)
148
+ predicted_label_id = int(prediction[0]['label'].split('_')[-1]) # Extract numeric label from 'LABEL_X'
149
+ return reverse_label_mapping[predicted_label_id]
150
+
151
+ # Responsive Layout - Uses full width
152
+ col1, col2 = st.columns([1.1, 1])
153
+
154
+ # Left Section - File Upload & CSV/Excel Display
155
+ with col1:
156
+ st.subheader("📂 Upload News Data")
157
+ uploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"])
158
+
159
+ if uploaded_file is not None:
160
+ # Determine the file extension
161
+ file_extension = uploaded_file.name.split('.')[-1]
162
+
163
+ if file_extension == 'csv':
164
+ df = pd.read_csv(uploaded_file)
165
+ elif file_extension == 'xlsx':
166
+ df = pd.read_excel(uploaded_file)
167
+
168
+ # Preprocess the content column and predict categories
169
+ if 'content' in df.columns:
170
+ df['preprocessed_content'] = df['content'].apply(preprocess_text)
171
+ df['class'] = df['preprocessed_content'].apply(predict_category)
172
+
173
+ # Drop the preprocessed_content column before displaying or saving
174
+ df_for_display = df.drop(columns=['preprocessed_content'], errors='ignore')
175
+ df_for_download = df.drop(columns=['preprocessed_content'], errors='ignore')
176
+
177
+ # Download button
178
+ st.download_button(
179
+ label="⬇️ Download Processed Data",
180
+ data=df_for_download.to_csv(index=False).encode('utf-8'),
181
+ file_name="output.csv",
182
+ mime="text/csv"
183
+ )
184
+
185
+ # CSV Preview Box
186
+ st.markdown("<div class='csv-box'><h4>📜 CSV/Excel Preview</h4></div>", unsafe_allow_html=True)
187
+ st.dataframe(df_for_display, use_container_width=True)
188
+
189
+
190
+ # Right Section - Q&A Interface
191
+ with col2:
192
+ st.subheader("🤖 AI Assistant")
193
+
194
+ # Answer Display Box (Initially Empty)
195
+ answer_placeholder = st.empty()
196
+ answer_placeholder.markdown("<div class='answer-box'></div>", unsafe_allow_html=True)
197
+
198
+ # Question Input
199
+ st.markdown("### 🔍 Ask Your Question:")
200
+ user_question = st.text_input("Enter your question here", label_visibility="hidden") # Hides the label
201
+
202
+ # Button & Answer Display
203
+ if st.button("🔮 Get Answer"):
204
+ if user_question.strip() and uploaded_file is not None:
205
+ # Ensure the DataFrame has the required content column
206
+ if 'content' in df.columns:
207
+ context = df['content'].dropna().tolist() # Use the content column as context
208
+
209
+ # Generate embeddings for the context and the question
210
+ context_embeddings = sentence_model.encode(context)
211
+ question_embedding = sentence_model.encode([user_question])
212
+
213
+ # Calculate cosine similarity
214
+ similarities = cosine_similarity(question_embedding, context_embeddings)
215
+ top_indices = similarities[0].argsort()[-5:][::-1] # Get top 5 similar rows
216
+
217
+ # Prepare the top 5 similar context rows
218
+ top_context = "\n".join([context[i] for i in top_indices])
219
+
220
+ # Get answer from Hugging Face model using top context
221
+ result = qa_pipeline(question=user_question, context=top_context)
222
+ answer = result['answer']
223
+ else:
224
+ answer = "⚠️ File does not contain a 'content' column!"
225
+ else:
226
+ answer = "⚠️ Please upload a valid file first!"
227
+
228
+ answer_placeholder.markdown(f"<div class='answer-box'>{answer}</div>", unsafe_allow_html=True)
229
+