pujanpaudel commited on
Commit
9cfd770
·
verified ·
1 Parent(s): cb6bafd

Rename appnamechanged.py to app.py

Browse files
Files changed (2) hide show
  1. app.py +199 -0
  2. appnamechanged.py +0 -199
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ from sklearn.feature_extraction.text import TfidfVectorizer
5
+ from sklearn.metrics.pairwise import cosine_similarity
6
+ import textwrap
7
+
8
+ # Page configuration
9
+ st.set_page_config(
10
+ page_title="Article Recommender",
11
+ layout="wide"
12
+ )
13
+
14
+ # Custom CSS with improved visibility
15
+ st.markdown("""
16
+ <style>
17
+ .article-card {
18
+ background-color: #ffffff;
19
+ padding: 1.5rem;
20
+ border-radius: 10px;
21
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
22
+ margin-bottom: 1rem;
23
+ color: #1f1f1f; /* Dark text color for contrast */
24
+ }
25
+ .article-title {
26
+ color: #1f1f1f;
27
+ font-size: 1.5rem;
28
+ margin-bottom: 1rem;
29
+ font-weight: bold;
30
+ }
31
+ .article-preview {
32
+ color: #2d2d2d; /* Darker grey for better visibility */
33
+ font-size: 1rem;
34
+ line-height: 1.6;
35
+ }
36
+ .article-full-text {
37
+ color: #2d2d2d;
38
+ font-size: 1.1rem;
39
+ line-height: 1.8;
40
+ white-space: pre-wrap; /* Preserve formatting */
41
+ }
42
+ .recommendation-card {
43
+ background-color: #f8f9fa;
44
+ padding: 1rem;
45
+ border-radius: 8px;
46
+ margin-bottom: 1rem;
47
+ border: 1px solid #e9ecef;
48
+ }
49
+ .recommendation-title {
50
+ color: #1f1f1f;
51
+ font-size: 1.2rem;
52
+ margin-bottom: 0.5rem;
53
+ font-weight: bold;
54
+ }
55
+ .recommendation-preview {
56
+ color: #2d2d2d;
57
+ font-size: 0.9rem;
58
+ line-height: 1.5;
59
+ }
60
+ .page-navigation {
61
+ display: flex;
62
+ justify-content: center;
63
+ gap: 1rem;
64
+ margin: 2rem 0;
65
+ }
66
+ .search-results {
67
+ margin: 1rem 0;
68
+ padding: 0.5rem;
69
+ background-color: #e9ecef;
70
+ border-radius: 5px;
71
+ color: #1f1f1f;
72
+ }
73
+ /* Override Streamlit's default text color */
74
+ .stMarkdown, .stText {
75
+ color: #1f1f1f !important;
76
+ }
77
+ </style>
78
+ """, unsafe_allow_html=True)
79
+
80
+ # Load and prepare data functions (unchanged)
81
+ @st.cache_data
82
+ def load_data():
83
+ df = pd.read_csv("cleaned.csv")
84
+ train_df = pd.read_csv("training.csv")
85
+ return (df,train_df)
86
+
87
+ @st.cache_resource
88
+ def prepare_similarity_matrix(df):
89
+ tfidf = TfidfVectorizer(max_features=5000)
90
+ tf_vectors = tfidf.fit_transform(df["data"]).toarray()
91
+ tf_similarity = cosine_similarity(tf_vectors)
92
+ return tf_similarity
93
+
94
+ def get_recommended_articles(title, df, tf_similarity):
95
+ title_idx = df[df["title"] == title].index[0]
96
+ similar_idx_scores = list(enumerate(tf_similarity[title_idx]))
97
+ sorted_similar_idx = sorted(similar_idx_scores, key=lambda x: x[1], reverse=True)
98
+ recommended_idx = sorted_similar_idx[1:4]
99
+ return recommended_idx
100
+
101
+ def truncate_text(text, max_words=50):
102
+ return " ".join(text.split()[:max_words]) + "..."
103
+
104
+ # Load data
105
+ df,train_df = load_data()
106
+ tf_similarity = prepare_similarity_matrix(train_df)
107
+
108
+ # Initialize session state
109
+ if 'page' not in st.session_state:
110
+ st.session_state.page = 'home'
111
+
112
+ # Sidebar with improved visibility
113
+ with st.sidebar:
114
+ st.title("Navigation")
115
+ if st.button("🏠 Home", use_container_width=True):
116
+ st.session_state.page = 'home'
117
+ st.rerun()
118
+
119
+ st.markdown("---")
120
+ search_query = st.text_input("🔍 Search Articles:")
121
+
122
+ # Main content
123
+ if st.session_state.page == 'home':
124
+ st.title("📚 Article Collection")
125
+
126
+ # Search functionality
127
+ if search_query:
128
+ mask = (df["title"].str.contains(search_query, case=False)) | \
129
+ (df["text"].str.contains(search_query, case=False))
130
+ filtered_df = df[mask]
131
+ st.markdown(f"""
132
+ <div class="search-results">
133
+ 📊 Found {len(filtered_df)} articles matching '{search_query}'
134
+ </div>
135
+ """, unsafe_allow_html=True)
136
+ else:
137
+ filtered_df = df
138
+
139
+ # Pagination
140
+ articles_per_page = 10
141
+ total_pages = len(filtered_df) // articles_per_page + (1 if len(filtered_df) % articles_per_page > 0 else 0)
142
+ col1, col2, col3 = st.columns([2, 3, 2])
143
+ with col2:
144
+ page_number = st.number_input("Page", min_value=1, max_value=max(1, total_pages), value=1) - 1
145
+
146
+ start_idx = page_number * articles_per_page
147
+ end_idx = start_idx + articles_per_page
148
+ page_df = filtered_df.iloc[start_idx:end_idx]
149
+
150
+ # Display articles
151
+ for _, row in page_df.iterrows():
152
+ st.markdown(f"""
153
+ <div class="article-card">
154
+ <div class="article-title">{row["title"]}</div>
155
+ <div class="article-preview">{truncate_text(row["text"])}</div>
156
+ </div>
157
+ """, unsafe_allow_html=True)
158
+ if st.button("📖 Read Full Article", key=f"read_{_}"):
159
+ st.session_state.page = 'article'
160
+ st.session_state.article_title = row["title"]
161
+ st.rerun()
162
+
163
+ else: # Article page
164
+ # Back button in sidebar
165
+ if st.sidebar.button("← Back to Articles", use_container_width=True):
166
+ st.session_state.page = 'home'
167
+ st.rerun()
168
+
169
+ # Display full article
170
+ article_data = df[df["title"] == st.session_state.article_title].iloc[0]
171
+
172
+ st.title(article_data["title"])
173
+
174
+ # Article container with improved visibility
175
+ st.markdown(f"""
176
+ <div class="article-card">
177
+ <div class="article-full-text">
178
+ {article_data["text"]}
179
+ </div>
180
+ </div>
181
+ """, unsafe_allow_html=True)
182
+
183
+ # Recommendations section
184
+ st.markdown("---")
185
+ st.subheader("📚 Recommended Articles")
186
+ recommended_articles = get_recommended_articles(st.session_state.article_title, df, tf_similarity)
187
+
188
+ cols = st.columns(3)
189
+ for idx, (article_idx, similarity_score) in enumerate(recommended_articles):
190
+ with cols[idx]:
191
+ st.markdown(f"""
192
+ <div class="recommendation-card">
193
+ <div class="recommendation-title">{df['title'].iloc[article_idx]}</div>
194
+ <div class="recommendation-preview">{truncate_text(df["text"].iloc[article_idx], max_words=30)}</div>
195
+ </div>
196
+ """, unsafe_allow_html=True)
197
+ if st.button("📖 Read This Article", key=f"rec_{article_idx}"):
198
+ st.session_state.article_title = df["title"].iloc[article_idx]
199
+ st.rerun()
appnamechanged.py DELETED
@@ -1,199 +0,0 @@
1
- # import streamlit as st
2
- # import pandas as pd
3
- # import numpy as np
4
- # from sklearn.feature_extraction.text import TfidfVectorizer
5
- # from sklearn.metrics.pairwise import cosine_similarity
6
- # import textwrap
7
-
8
- # # Page configuration
9
- # st.set_page_config(
10
- # page_title="Article Recommender",
11
- # layout="wide"
12
- # )
13
-
14
- # # Custom CSS with improved visibility
15
- # st.markdown("""
16
- # <style>
17
- # .article-card {
18
- # background-color: #ffffff;
19
- # padding: 1.5rem;
20
- # border-radius: 10px;
21
- # box-shadow: 0 2px 4px rgba(0,0,0,0.1);
22
- # margin-bottom: 1rem;
23
- # color: #1f1f1f; /* Dark text color for contrast */
24
- # }
25
- # .article-title {
26
- # color: #1f1f1f;
27
- # font-size: 1.5rem;
28
- # margin-bottom: 1rem;
29
- # font-weight: bold;
30
- # }
31
- # .article-preview {
32
- # color: #2d2d2d; /* Darker grey for better visibility */
33
- # font-size: 1rem;
34
- # line-height: 1.6;
35
- # }
36
- # .article-full-text {
37
- # color: #2d2d2d;
38
- # font-size: 1.1rem;
39
- # line-height: 1.8;
40
- # white-space: pre-wrap; /* Preserve formatting */
41
- # }
42
- # .recommendation-card {
43
- # background-color: #f8f9fa;
44
- # padding: 1rem;
45
- # border-radius: 8px;
46
- # margin-bottom: 1rem;
47
- # border: 1px solid #e9ecef;
48
- # }
49
- # .recommendation-title {
50
- # color: #1f1f1f;
51
- # font-size: 1.2rem;
52
- # margin-bottom: 0.5rem;
53
- # font-weight: bold;
54
- # }
55
- # .recommendation-preview {
56
- # color: #2d2d2d;
57
- # font-size: 0.9rem;
58
- # line-height: 1.5;
59
- # }
60
- # .page-navigation {
61
- # display: flex;
62
- # justify-content: center;
63
- # gap: 1rem;
64
- # margin: 2rem 0;
65
- # }
66
- # .search-results {
67
- # margin: 1rem 0;
68
- # padding: 0.5rem;
69
- # background-color: #e9ecef;
70
- # border-radius: 5px;
71
- # color: #1f1f1f;
72
- # }
73
- # /* Override Streamlit's default text color */
74
- # .stMarkdown, .stText {
75
- # color: #1f1f1f !important;
76
- # }
77
- # </style>
78
- # """, unsafe_allow_html=True)
79
-
80
- # # Load and prepare data functions (unchanged)
81
- # @st.cache_data
82
- # def load_data():
83
- # df = pd.read_csv("cleaned.csv")
84
- # train_df = pd.read_csv("training.csv")
85
- # return (df,train_df)
86
-
87
- # @st.cache_resource
88
- # def prepare_similarity_matrix(df):
89
- # tfidf = TfidfVectorizer(max_features=5000)
90
- # tf_vectors = tfidf.fit_transform(df["data"]).toarray()
91
- # tf_similarity = cosine_similarity(tf_vectors)
92
- # return tf_similarity
93
-
94
- # def get_recommended_articles(title, df, tf_similarity):
95
- # title_idx = df[df["title"] == title].index[0]
96
- # similar_idx_scores = list(enumerate(tf_similarity[title_idx]))
97
- # sorted_similar_idx = sorted(similar_idx_scores, key=lambda x: x[1], reverse=True)
98
- # recommended_idx = sorted_similar_idx[1:4]
99
- # return recommended_idx
100
-
101
- # def truncate_text(text, max_words=50):
102
- # return " ".join(text.split()[:max_words]) + "..."
103
-
104
- # # Load data
105
- # df,train_df = load_data()
106
- # tf_similarity = prepare_similarity_matrix(train_df)
107
-
108
- # # Initialize session state
109
- # if 'page' not in st.session_state:
110
- # st.session_state.page = 'home'
111
-
112
- # # Sidebar with improved visibility
113
- # with st.sidebar:
114
- # st.title("Navigation")
115
- # if st.button("🏠 Home", use_container_width=True):
116
- # st.session_state.page = 'home'
117
- # st.rerun()
118
-
119
- # st.markdown("---")
120
- # search_query = st.text_input("🔍 Search Articles:")
121
-
122
- # # Main content
123
- # if st.session_state.page == 'home':
124
- # st.title("📚 Article Collection")
125
-
126
- # # Search functionality
127
- # if search_query:
128
- # mask = (df["title"].str.contains(search_query, case=False)) | \
129
- # (df["text"].str.contains(search_query, case=False))
130
- # filtered_df = df[mask]
131
- # st.markdown(f"""
132
- # <div class="search-results">
133
- # 📊 Found {len(filtered_df)} articles matching '{search_query}'
134
- # </div>
135
- # """, unsafe_allow_html=True)
136
- # else:
137
- # filtered_df = df
138
-
139
- # # Pagination
140
- # articles_per_page = 10
141
- # total_pages = len(filtered_df) // articles_per_page + (1 if len(filtered_df) % articles_per_page > 0 else 0)
142
- # col1, col2, col3 = st.columns([2, 3, 2])
143
- # with col2:
144
- # page_number = st.number_input("Page", min_value=1, max_value=max(1, total_pages), value=1) - 1
145
-
146
- # start_idx = page_number * articles_per_page
147
- # end_idx = start_idx + articles_per_page
148
- # page_df = filtered_df.iloc[start_idx:end_idx]
149
-
150
- # # Display articles
151
- # for _, row in page_df.iterrows():
152
- # st.markdown(f"""
153
- # <div class="article-card">
154
- # <div class="article-title">{row["title"]}</div>
155
- # <div class="article-preview">{truncate_text(row["text"])}</div>
156
- # </div>
157
- # """, unsafe_allow_html=True)
158
- # if st.button("📖 Read Full Article", key=f"read_{_}"):
159
- # st.session_state.page = 'article'
160
- # st.session_state.article_title = row["title"]
161
- # st.rerun()
162
-
163
- # else: # Article page
164
- # # Back button in sidebar
165
- # if st.sidebar.button("← Back to Articles", use_container_width=True):
166
- # st.session_state.page = 'home'
167
- # st.rerun()
168
-
169
- # # Display full article
170
- # article_data = df[df["title"] == st.session_state.article_title].iloc[0]
171
-
172
- # st.title(article_data["title"])
173
-
174
- # # Article container with improved visibility
175
- # st.markdown(f"""
176
- # <div class="article-card">
177
- # <div class="article-full-text">
178
- # {article_data["text"]}
179
- # </div>
180
- # </div>
181
- # """, unsafe_allow_html=True)
182
-
183
- # # Recommendations section
184
- # st.markdown("---")
185
- # st.subheader("📚 Recommended Articles")
186
- # recommended_articles = get_recommended_articles(st.session_state.article_title, df, tf_similarity)
187
-
188
- # cols = st.columns(3)
189
- # for idx, (article_idx, similarity_score) in enumerate(recommended_articles):
190
- # with cols[idx]:
191
- # st.markdown(f"""
192
- # <div class="recommendation-card">
193
- # <div class="recommendation-title">{df['title'].iloc[article_idx]}</div>
194
- # <div class="recommendation-preview">{truncate_text(df["text"].iloc[article_idx], max_words=30)}</div>
195
- # </div>
196
- # """, unsafe_allow_html=True)
197
- # if st.button("📖 Read This Article", key=f"rec_{article_idx}"):
198
- # st.session_state.article_title = df["title"].iloc[article_idx]
199
- # st.rerun()