Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from EnYa32/RestaurantRecommendation: direct link, hf CLI and curl.
- Browser
- Download file 5.41 kB
-
https://huggingface.co/spaces/EnYa32/RestaurantRecommendation/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/EnYa32/RestaurantRecommendation/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/EnYa32/RestaurantRecommendation/resolve/main/src/streamlit_app.py
5.41 kB
| import numpy as np | |
| import pandas as pd | |
| import joblib | |
| import streamlit as st | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| st.set_page_config(page_title="Restaurant Recommendation System", page_icon="🍽️", layout="wide") | |
| st.title("🍽️ Restaurant Recommendation System") | |
| st.write("Select a restaurant and get similar restaurant recommendations using **TF-IDF + Cosine Similarity**.") | |
| # ---------------------------- | |
| # Load artifacts (cached) | |
| # ---------------------------- | |
| def load_artifacts(): | |
| # If your files are in repo root, remove 'src/' from these paths | |
| tfidf = joblib.load("src/tfidf.pkl") | |
| df = pd.read_pickle("src/restaurants_df.pkl") | |
| # Ensure required columns exist | |
| required_cols = {"Name", "Type", "Location", "Price_Range", "Comments", "Trip_advisor Url"} | |
| missing = required_cols - set(df.columns) | |
| if missing: | |
| raise ValueError(f"Missing required columns in DataFrame: {missing}") | |
| # Ensure combined text column exists | |
| if "combined_columns" not in df.columns: | |
| df["Type"] = df["Type"].fillna("Unknown") | |
| df["Comments"] = df["Comments"].fillna("") | |
| df["combined_columns"] = ( | |
| df["Type"].astype(str) + " " + | |
| df["Location"].astype(str) + " " + | |
| df["Price_Range"].astype(str) + " " + | |
| df["Comments"].astype(str) | |
| ) | |
| # Normalize text | |
| text = df["combined_columns"].astype(str).str.lower() | |
| # Build similarity matrix at runtime (lightweight deployment) | |
| X = tfidf.transform(text) | |
| sim = cosine_similarity(X) | |
| return df, sim | |
| # ---------------------------- | |
| # Recommender with scores | |
| # ---------------------------- | |
| def recommend_with_scores(name, df, sim, top_n=5, same_location_only=False, price_filter="All"): | |
| # Safety: if list is empty or name not found | |
| matches = df.index[df["Name"] == name].tolist() | |
| if not matches: | |
| return pd.DataFrame({"Message": [f"'{name}' not found in dataset."]}) | |
| idx = matches[0] | |
| scores = sim[idx] | |
| # Sort indices by similarity (desc), exclude itself | |
| ranked_idx = np.argsort(scores)[::-1] | |
| ranked_idx = ranked_idx[ranked_idx != idx] | |
| # Build candidates dataframe | |
| candidates = df.loc[ | |
| ranked_idx, | |
| ["Name", "Type", "Location", "Price_Range", "Trip_advisor Url"] | |
| ].copy() | |
| candidates["Similarity"] = scores[ranked_idx] | |
| # Optional filters | |
| if same_location_only: | |
| selected_loc = df.loc[idx, "Location"] | |
| candidates = candidates[candidates["Location"] == selected_loc] | |
| if price_filter and price_filter != "All": | |
| candidates = candidates[candidates["Price_Range"] == price_filter] | |
| # Take top_n | |
| result = candidates.head(top_n).copy() | |
| result["Similarity"] = result["Similarity"].round(3) | |
| # Clickable link column (Markdown) | |
| result["TripAdvisor Link"] = result["Trip_advisor Url"].apply( | |
| lambda u: f"[Open]({u})" if isinstance(u, str) and u.startswith("http") else "" | |
| ) | |
| # Keep clean columns | |
| result = result[["Name", "Type", "Location", "Price_Range", "Similarity", "TripAdvisor Link"]] | |
| result.reset_index(drop=True, inplace=True) | |
| result.index += 1 | |
| return result | |
| # ---------------------------- | |
| # Main app | |
| # ---------------------------- | |
| try: | |
| df, sim_matrix = load_artifacts() | |
| except Exception as e: | |
| st.error("❌ Could not load artifacts. Please check file paths and required columns.") | |
| st.exception(e) | |
| st.stop() | |
| # ✅ DEBUG (damit du sofort siehst, ob df geladen wurde) | |
| with st.expander("🔍 Debug (open if app looks empty)"): | |
| st.write("Number of rows:", len(df)) | |
| st.write("Columns:", list(df.columns)) | |
| st.dataframe(df.head(5), use_container_width=True) | |
| # Sidebar settings (optional but stable) | |
| st.sidebar.header("⚙️ Settings") | |
| top_n = st.sidebar.slider("Number of recommendations", 3, 20, 5, 1) | |
| same_location_only = st.sidebar.checkbox("Recommend only from the same location", value=False) | |
| price_options = ["All"] + sorted(df["Price_Range"].dropna().astype(str).unique().tolist()) | |
| price_filter = st.sidebar.selectbox("Price range filter", price_options, index=0) | |
| # Dropdown (IMPORTANT: ensure list not empty) | |
| restaurant_list = df["Name"].dropna().astype(str).unique().tolist() | |
| restaurant_list.sort() | |
| if len(restaurant_list) == 0: | |
| st.error("No restaurant names found. Please check your dataset.") | |
| st.stop() | |
| selected_restaurant = st.selectbox("Select a restaurant", restaurant_list) | |
| if st.button("Recommend"): | |
| st.subheader(f"Recommendations for: {selected_restaurant}") | |
| recs = recommend_with_scores( | |
| selected_restaurant, | |
| df, | |
| sim_matrix, | |
| top_n=top_n, | |
| same_location_only=same_location_only, | |
| price_filter=price_filter | |
| ) | |
| # Use markdown table so links are visible | |
| st.dataframe(recs, use_container_width=True) | |
| st.caption("Similarity closer to 1.0 means stronger similarity.") | |
| st.divider() | |
| with st.expander("ℹ️ How it works"): | |
| st.write( | |
| """ | |
| - This is a **content-based recommendation system**. | |
| - Restaurant data (type, location, price range, comments) is combined into one text feature. | |
| - Text is vectorized using **TF-IDF**. | |
| - Similar restaurants are found with **Cosine Similarity**. | |
| - The similarity matrix is computed at runtime to keep the Space lightweight. | |
| """ | |
| ) |