handex commited on
Commit
450f90e
·
verified ·
1 Parent(s): bba42e2

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +8 -22
src/streamlit_app.py CHANGED
@@ -14,7 +14,7 @@ DATA_FILE_PATH = 'src/articles.csv'
14
  # Number of recommendations to display
15
  NUM_RECOMMENDATIONS = 5
16
 
17
- # --- Data Loading and Preparation (Removed mock data dependency) ---
18
  @st.cache_data
19
  def load_and_prepare_data():
20
  """
@@ -25,8 +25,8 @@ def load_and_prepare_data():
25
 
26
  if os.path.exists(DATA_FILE_PATH):
27
  try:
28
- df = pd.read_csv(DATA_FILE_PATH, encoding='latin1')
29
- st.success(f"Data loaded successfully from {DATA_FILE_PATH}.")
30
  except Exception as e:
31
  st.error(f"Error reading {DATA_FILE_PATH}. Please check file integrity and format (CSV). Error: {e}")
32
  else:
@@ -53,7 +53,6 @@ def fit_or_load_models(df):
53
  """
54
  # Check if the necessary columns exist before proceeding
55
  if df.empty or 'Article' not in df.columns or 'Title' not in df.columns:
56
- # This check should be redundant if load_and_prepare_data works, but good for defense
57
  return None, None, None
58
 
59
  if os.path.exists(VECTORIZER_PATH) and os.path.exists(TFIDF_MATRIX_PATH):
@@ -64,7 +63,7 @@ def fit_or_load_models(df):
64
 
65
  # Recalculate cosine similarity (This is fast on the loaded matrix)
66
  cosine_sim = cosine_similarity(tfidf_matrix)
67
- st.success("Models loaded successfully from disk.")
68
  return tfidf, tfidf_matrix, cosine_sim
69
  except Exception as e:
70
  st.error(f"Error loading models. Recalculating: {e}")
@@ -85,7 +84,7 @@ def fit_or_load_models(df):
85
  # Save models for future runs
86
  joblib.dump(tfidf, VECTORIZER_PATH)
87
  joblib.dump(tfidf_matrix, TFIDF_MATRIX_PATH)
88
- st.success("Model calculation complete and saved.")
89
 
90
  return tfidf, tfidf_matrix, cosine_sim
91
 
@@ -110,7 +109,7 @@ def get_recommendations(article_index, cosine_sim_matrix, df, num_recommendation
110
  # Get the indices of the top N recommended articles (these are positional indices)
111
  top_n_indices = [i[0] for i in top_n_recommendations]
112
 
113
- # --- CRITICAL FIX: Use list indexing instead of DataFrame .iloc to guarantee positional lookup ---
114
  title_list = df["Title"].tolist()
115
  recommended_titles = [title_list[i] for i in top_n_indices]
116
 
@@ -126,7 +125,7 @@ def app():
126
  st.set_page_config(page_title="Article Recommendation System", layout="wide")
127
 
128
  st.title("📄 Content-Based Article Recommender")
129
- st.markdown("This system uses TF-IDF vectorization and Cosine Similarity to recommend articles based on content matching.")
130
 
131
  # 1. Load Data
132
  df = load_and_prepare_data()
@@ -192,19 +191,6 @@ def app():
192
  st.markdown("### Article Title (Similarity Score)")
193
  for title, score in recommendations_list:
194
  st.markdown(f"**{title}** - *({score}%)*")
195
-
196
- st.markdown("""
197
- ---
198
- **Methodology:**
199
- 1. **Vectorization:** TF-IDF (Term Frequency-Inverse Document Frequency) transforms article text into numerical vectors.
200
- 2. **Similarity:** Cosine Similarity measures the angle between vectors to determine content similarity.
201
- 3. **Result:** Articles with the smallest angle (highest score) are recommended.
202
- """)
203
-
204
- # Add a section to show the current article's content
205
- st.subheader("Current Article Content:")
206
- article_content = df.iloc[selected_index]['Article']
207
- st.markdown(f"*{article_content}*")
208
-
209
  if __name__ == "__main__":
210
  app()
 
14
  # Number of recommendations to display
15
  NUM_RECOMMENDATIONS = 5
16
 
17
+ # --- Data Loading and Preparation ---
18
  @st.cache_data
19
  def load_and_prepare_data():
20
  """
 
25
 
26
  if os.path.exists(DATA_FILE_PATH):
27
  try:
28
+ df = pd.read_csv(DATA_FILE_PATH,encoding='latin1')
29
+ # Removed st.success(f"Data loaded successfully...")
30
  except Exception as e:
31
  st.error(f"Error reading {DATA_FILE_PATH}. Please check file integrity and format (CSV). Error: {e}")
32
  else:
 
53
  """
54
  # Check if the necessary columns exist before proceeding
55
  if df.empty or 'Article' not in df.columns or 'Title' not in df.columns:
 
56
  return None, None, None
57
 
58
  if os.path.exists(VECTORIZER_PATH) and os.path.exists(TFIDF_MATRIX_PATH):
 
63
 
64
  # Recalculate cosine similarity (This is fast on the loaded matrix)
65
  cosine_sim = cosine_similarity(tfidf_matrix)
66
+ # Removed st.success("Models loaded successfully...")
67
  return tfidf, tfidf_matrix, cosine_sim
68
  except Exception as e:
69
  st.error(f"Error loading models. Recalculating: {e}")
 
84
  # Save models for future runs
85
  joblib.dump(tfidf, VECTORIZER_PATH)
86
  joblib.dump(tfidf_matrix, TFIDF_MATRIX_PATH)
87
+ # Removed st.success("Model calculation complete...")
88
 
89
  return tfidf, tfidf_matrix, cosine_sim
90
 
 
109
  # Get the indices of the top N recommended articles (these are positional indices)
110
  top_n_indices = [i[0] for i in top_n_recommendations]
111
 
112
+ # Use list indexing instead of DataFrame .iloc to guarantee positional lookup
113
  title_list = df["Title"].tolist()
114
  recommended_titles = [title_list[i] for i in top_n_indices]
115
 
 
125
  st.set_page_config(page_title="Article Recommendation System", layout="wide")
126
 
127
  st.title("📄 Content-Based Article Recommender")
128
+ st.markdown("Select an article from the sidebar to see the top **5** most relevant recommendations.")
129
 
130
  # 1. Load Data
131
  df = load_and_prepare_data()
 
191
  st.markdown("### Article Title (Similarity Score)")
192
  for title, score in recommendations_list:
193
  st.markdown(f"**{title}** - *({score}%)*")
194
+
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  if __name__ == "__main__":
196
  app()