wmcandrew commited on
Commit
cf3ef88
Β·
verified Β·
1 Parent(s): 822afd8

Upload huggingface_app.py

Browse files
Files changed (1) hide show
  1. huggingface_app.py +231 -0
huggingface_app.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib
5
+ matplotlib.use('Agg')
6
+ import matplotlib.pyplot as plt
7
+ import seaborn as sns
8
+ from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
9
+ from sklearn.ensemble import RandomForestClassifier
10
+ from sklearn.model_selection import train_test_split
11
+ from sklearn.preprocessing import LabelEncoder
12
+ from statsmodels.tsa.arima.model import ARIMA
13
+ import warnings
14
+ warnings.filterwarnings('ignore')
15
+
16
+ # ─── DATA SETUP (runs once on app load) ───
17
+ np.random.seed(42)
18
+
19
+ n_listings = 500
20
+ neighbourhoods = ['Le Marais', 'Montmartre', 'Latin Quarter', 'Bastille',
21
+ 'Belleville', 'Oberkampf', 'Saint-Germain', 'Pigalle',
22
+ 'Batignolles', 'Menilmontant', 'Republique', 'Nation']
23
+ room_types = ['Entire home/apt', 'Private room', 'Shared room']
24
+
25
+ listings = pd.DataFrame({
26
+ 'listing_id': range(1, n_listings + 1),
27
+ 'neighbourhood': np.random.choice(neighbourhoods, n_listings),
28
+ 'room_type': np.random.choice(room_types, n_listings, p=[0.55, 0.38, 0.07]),
29
+ 'accommodates': np.random.choice([1,2,3,4,5,6], n_listings, p=[0.1,0.3,0.25,0.2,0.1,0.05]),
30
+ 'bedrooms': np.random.choice([0,1,2,3], n_listings, p=[0.15,0.5,0.25,0.1]),
31
+ 'minimum_nights': np.random.choice([1,2,3,5,7,30], n_listings, p=[0.3,0.25,0.2,0.1,0.1,0.05]),
32
+ 'number_of_reviews': np.random.poisson(40, n_listings),
33
+ 'reviews_per_month': np.round(np.random.exponential(2.5, n_listings), 2),
34
+ 'host_is_superhost': np.random.choice([0, 1], n_listings, p=[0.7, 0.3]),
35
+ 'instant_bookable': np.random.choice([0, 1], n_listings, p=[0.4, 0.6]),
36
+ })
37
+
38
+ base_prices = {'Entire home/apt': 120, 'Private room': 55, 'Shared room': 25}
39
+ premium = ['Le Marais', 'Saint-Germain', 'Latin Quarter', 'Montmartre']
40
+ listings['price'] = listings.apply(
41
+ lambda r: base_prices[r['room_type']] * (1.3 if r['neighbourhood'] in premium else 1.0)
42
+ * np.random.uniform(0.6, 1.6), axis=1).round(2)
43
+ listings['review_scores_rating'] = np.clip(
44
+ np.where(listings['host_is_superhost'] == 1,
45
+ np.random.normal(4.7, 0.2, n_listings),
46
+ np.random.normal(4.3, 0.4, n_listings)), 3.0, 5.0).round(2)
47
+
48
+ # Generate reviews
49
+ review_templates = {
50
+ 'positive': ["Amazing location, very clean and the host was super responsive!",
51
+ "Perfect apartment for our stay. Walking distance to everything.",
52
+ "Loved the cozy atmosphere. Would definitely come back!",
53
+ "Great value for money. The neighborhood is lovely.",
54
+ "Exceeded expectations! Beautiful decor and comfortable bed."],
55
+ 'neutral': ["Decent place, a bit noisy at night but overall okay.",
56
+ "Good location but the apartment was smaller than expected.",
57
+ "It was fine for the price. Nothing special but clean enough."],
58
+ 'negative': ["Disappointed. The photos were misleading and it was dirty.",
59
+ "Would not recommend. Noisy neighbors and broken appliances.",
60
+ "Not worth the price at all. Bed was uncomfortable."]
61
+ }
62
+
63
+ reviews_list = []
64
+ for _ in range(5000):
65
+ lid = np.random.choice(listings['listing_id'])
66
+ rating = listings.loc[listings['listing_id'] == lid, 'review_scores_rating'].values[0]
67
+ probs = [0.75, 0.2, 0.05] if rating >= 4.5 else ([0.5, 0.35, 0.15] if rating >= 4.0 else [0.25, 0.35, 0.4])
68
+ cat = np.random.choice(['positive', 'neutral', 'negative'], p=probs)
69
+ reviews_list.append({'listing_id': lid, 'comments': np.random.choice(review_templates[cat])})
70
+ reviews = pd.DataFrame(reviews_list)
71
+
72
+ # Sentiment
73
+ analyzer = SentimentIntensityAnalyzer()
74
+ reviews['sentiment'] = reviews['comments'].apply(lambda x: analyzer.polarity_scores(str(x))['compound'])
75
+ listing_sent = reviews.groupby('listing_id')['sentiment'].mean().reset_index()
76
+ listing_sent.columns = ['listing_id', 'avg_sentiment']
77
+ listings = listings.merge(listing_sent, on='listing_id', how='left').fillna(0)
78
+
79
+ # Train Random Forest
80
+ le_room = LabelEncoder()
81
+ le_hood = LabelEncoder()
82
+ listings['room_enc'] = le_room.fit_transform(listings['room_type'])
83
+ listings['hood_enc'] = le_hood.fit_transform(listings['neighbourhood'])
84
+ med_rating = listings['review_scores_rating'].median()
85
+ med_reviews = listings['reviews_per_month'].median()
86
+ listings['HighPerformer'] = ((listings['review_scores_rating'] >= med_rating) &
87
+ (listings['reviews_per_month'] >= med_reviews)).astype(int)
88
+
89
+ features = ['price','accommodates','bedrooms','minimum_nights','number_of_reviews',
90
+ 'host_is_superhost','instant_bookable','avg_sentiment','room_enc','hood_enc']
91
+ X = listings[features]
92
+ y = listings['HighPerformer']
93
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
94
+ rf = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
95
+ rf.fit(X_train, y_train)
96
+
97
+ # ─── APP FUNCTIONS ───
98
+
99
+ def neighbourhood_dashboard(neighbourhood):
100
+ subset = listings[listings['neighbourhood'] == neighbourhood]
101
+ n = len(subset)
102
+ avg_price = subset['price'].mean()
103
+ avg_sent = subset['avg_sentiment'].mean()
104
+ avg_rating = subset['review_scores_rating'].mean()
105
+ pct_superhost = subset['host_is_superhost'].mean() * 100
106
+ hp_pct = subset['HighPerformer'].mean() * 100
107
+
108
+ summary = f"""## {neighbourhood} Dashboard
109
+ | Metric | Value |
110
+ |--------|-------|
111
+ | Total Listings | {n} |
112
+ | Average Price | €{avg_price:.0f}/night |
113
+ | Average Sentiment | {avg_sent:.3f} |
114
+ | Average Rating | {avg_rating:.2f}/5.0 |
115
+ | Superhost % | {pct_superhost:.0f}% |
116
+ | High Performers | {hp_pct:.0f}% |
117
+
118
+ ### Recommendation
119
+ {"**Premium neighbourhood** β€” prices above city average. Focus on maintaining quality to justify pricing." if avg_price > listings['price'].mean() else "**Value neighbourhood** β€” room to increase prices if sentiment stays positive."}
120
+ """
121
+ # Chart
122
+ fig, axes = plt.subplots(1, 2, figsize=(12, 4))
123
+ subset['room_type'].value_counts().plot(kind='bar', ax=axes[0], color=['#3498db','#e67e22','#27ae60'])
124
+ axes[0].set_title(f'Room Types in {neighbourhood}')
125
+ axes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=30)
126
+ axes[1].hist(subset['price'], bins=15, color='#3498db', edgecolor='white')
127
+ axes[1].axvline(listings['price'].mean(), color='red', linestyle='--', label='City avg')
128
+ axes[1].set_title(f'Price Distribution in {neighbourhood}')
129
+ axes[1].set_xlabel('Price (€)')
130
+ axes[1].legend()
131
+ plt.tight_layout()
132
+ return summary, fig
133
+
134
+ def feature_importance_chart():
135
+ importances = pd.Series(rf.feature_importances_, index=features).sort_values(ascending=True)
136
+ fig, ax = plt.subplots(figsize=(10, 6))
137
+ importances.plot(kind='barh', ax=ax, color='#3498db', edgecolor='white')
138
+ ax.set_xlabel('Importance Score')
139
+ ax.set_title('What Makes an Airbnb Listing a High Performer?', fontsize=14, fontweight='bold')
140
+ plt.tight_layout()
141
+ accuracy = rf.score(X_test, y_test)
142
+ report = f"**Model Accuracy: {accuracy*100:.1f}%**\n\nTop 3 features: {', '.join(importances.tail(3).index.tolist()[::-1])}"
143
+ return report, fig
144
+
145
+ def price_forecast(neighbourhood):
146
+ subset = listings[listings['neighbourhood'] == neighbourhood]
147
+ base = subset['price'].mean()
148
+ months = pd.date_range('2023-01-01', periods=24, freq='MS')
149
+ trend = np.linspace(0, base * 0.15, 24)
150
+ seasonality = base * 0.1 * np.sin(np.linspace(0, 4*np.pi, 24))
151
+ noise = np.random.normal(0, base * 0.03, 24)
152
+ ts = pd.Series(base + trend + seasonality + noise, index=months)
153
+
154
+ model = ARIMA(ts, order=(1,1,1))
155
+ fitted = model.fit()
156
+ forecast = fitted.forecast(steps=6)
157
+ forecast_idx = pd.date_range(months[-1] + pd.DateOffset(months=1), periods=6, freq='MS')
158
+
159
+ fig, ax = plt.subplots(figsize=(12, 5))
160
+ ax.plot(ts.index, ts.values, 'b-o', markersize=4, label='Historical', linewidth=1.5)
161
+ ax.plot(forecast_idx, forecast.values, 'r--o', markersize=4, label='Forecast', linewidth=1.5)
162
+ ax.fill_between(forecast_idx, forecast.values*0.92, forecast.values*1.08, alpha=0.2, color='red')
163
+ ax.set_title(f'{neighbourhood} β€” 6-Month Price Forecast (ARIMA)', fontsize=14, fontweight='bold')
164
+ ax.set_ylabel('Average Price (€)')
165
+ ax.legend()
166
+ ax.grid(True, alpha=0.3)
167
+ plt.tight_layout()
168
+
169
+ change = ((forecast.values[-1] - ts.values[-1]) / ts.values[-1]) * 100
170
+ info = f"**Current avg: €{ts.values[-1]:.0f}** β†’ **Forecasted: €{forecast.values[-1]:.0f}** ({change:+.1f}% over 6 months)"
171
+ return info, fig
172
+
173
+ def sentiment_overview():
174
+ fig, axes = plt.subplots(1, 2, figsize=(14, 5))
175
+ hood_sent = listings.groupby('neighbourhood')['avg_sentiment'].mean().sort_values()
176
+ colors = ['#e74c3c' if v < 0.3 else '#f39c12' if v < 0.37 else '#27ae60' for v in hood_sent]
177
+ hood_sent.plot(kind='barh', ax=axes[0], color=colors)
178
+ axes[0].set_title('Sentiment by Neighbourhood')
179
+ axes[0].set_xlabel('Average Sentiment')
180
+ sh = listings.groupby('host_is_superhost')['avg_sentiment'].mean()
181
+ sh.index = ['Regular', 'Superhost']
182
+ sh.plot(kind='bar', ax=axes[1], color=['#3498db', '#e67e22'])
183
+ axes[1].set_title('Superhost Effect on Sentiment')
184
+ axes[1].set_xticklabels(axes[1].get_xticklabels(), rotation=0)
185
+ plt.tight_layout()
186
+ best = hood_sent.idxmax()
187
+ worst = hood_sent.idxmin()
188
+ info = f"**Best:** {best} ({hood_sent.max():.3f}) | **Worst:** {worst} ({hood_sent.min():.3f}) | **Superhost boost:** +{sh['Superhost']-sh['Regular']:.3f}"
189
+ return info, fig
190
+
191
+ # ─── BUILD APP ───
192
+ with gr.Blocks(title="Airbnb Pricing & Satisfaction Optimizer", theme=gr.themes.Soft()) as app:
193
+ gr.Markdown("""# 🏠 Airbnb Pricing & Guest Satisfaction Optimizer
194
+ *AI for Big Data Management β€” Group Project | ESCP Business School*
195
+
196
+ Analyze listing performance across Paris neighbourhoods using sentiment analysis,
197
+ random forest classification, and ARIMA price forecasting.
198
+ """)
199
+
200
+ with gr.Tab("πŸ“Š Neighbourhood Dashboard"):
201
+ gr.Markdown("Select a neighbourhood to see key metrics and pricing insights.")
202
+ hood_input = gr.Dropdown(choices=sorted(neighbourhoods), value='Le Marais', label="Neighbourhood")
203
+ hood_btn = gr.Button("Analyze", variant="primary")
204
+ hood_summary = gr.Markdown()
205
+ hood_chart = gr.Plot()
206
+ hood_btn.click(neighbourhood_dashboard, inputs=hood_input, outputs=[hood_summary, hood_chart])
207
+
208
+ with gr.Tab("🌲 Feature Importance"):
209
+ gr.Markdown("Which features most predict whether a listing will be a high performer?")
210
+ fi_btn = gr.Button("Show Feature Importance", variant="primary")
211
+ fi_text = gr.Markdown()
212
+ fi_chart = gr.Plot()
213
+ fi_btn.click(feature_importance_chart, outputs=[fi_text, fi_chart])
214
+
215
+ with gr.Tab("πŸ“ˆ Price Forecast"):
216
+ gr.Markdown("ARIMA(1,1,1) forecast of average listing prices for the next 6 months.")
217
+ fc_input = gr.Dropdown(choices=sorted(neighbourhoods), value='Le Marais', label="Neighbourhood")
218
+ fc_btn = gr.Button("Forecast", variant="primary")
219
+ fc_text = gr.Markdown()
220
+ fc_chart = gr.Plot()
221
+ fc_btn.click(price_forecast, inputs=fc_input, outputs=[fc_text, fc_chart])
222
+
223
+ with gr.Tab("πŸ’¬ Sentiment Analysis"):
224
+ gr.Markdown("Overview of guest sentiment across all neighbourhoods and host types.")
225
+ sa_btn = gr.Button("Show Sentiment Overview", variant="primary")
226
+ sa_text = gr.Markdown()
227
+ sa_chart = gr.Plot()
228
+ sa_btn.click(sentiment_overview, outputs=[sa_text, sa_chart])
229
+
230
+ if __name__ == "__main__":
231
+ app.launch()