Em4e commited on
Commit
ee2180d
Β·
verified Β·
1 Parent(s): 160f565

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +666 -131
app.py CHANGED
@@ -1,61 +1,84 @@
1
- # 1. MODIFY THE SIDEBAR INTERNET SIZE SELECTOR
2
- # Replace this section in the main() function:
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- st.sidebar.markdown("### 🎯 **Step 2: Test Settings**")
5
-
6
- num_tests = st.sidebar.select_slider(
7
- "How many tests to run?",
8
- options=[5, 10, 15, 20, 25, 30],
9
- value=10,
10
- help="More tests = more reliable results, but takes longer"
11
- )
12
-
13
- # CHANGE THIS PART:
14
- internet_size = st.sidebar.select_slider(
15
- "Internet simulation size",
16
- options=[
17
- "Large (100K sites)",
18
- "Very Large (250K sites)",
19
- "Huge (500K sites)",
20
- "Massive (750K sites)",
21
- "Ultra (1M sites)"
22
- ],
23
- value="Large (100K sites)",
24
- help="Larger = more realistic but much slower. WARNING: 500K+ may take several minutes per test!"
25
  )
26
 
27
- # Convert internet size to numbers
28
- size_map = {
29
- "Large (100K sites)": 100000,
30
- "Very Large (250K sites)": 250000,
31
- "Huge (500K sites)": 500000,
32
- "Massive (750K sites)": 750000,
33
- "Ultra (1M sites)": 1000000
34
- }
35
- www_nodes = size_map[internet_size]
36
-
37
- # 2. ADD PERFORMANCE WARNINGS
38
- # Add this right after the internet size selector:
39
-
40
- if www_nodes >= 500000:
41
- st.sidebar.warning(f"""
42
- ⚠️ **Performance Warning**:
43
- {internet_size} will be very slow!
44
- Expect 2-10 minutes per test.
45
- Consider using fewer tests.
46
- """)
47
- elif www_nodes >= 250000:
48
- st.sidebar.info(f"""
49
- ℹ️ **Note**: {internet_size} may take
50
- 30-60 seconds per test.
51
- """)
52
 
53
- # 3. OPTIMIZE THE WWW GRAPH CREATION FUNCTION
54
- # Replace the create_www_graph_networkit function with this optimized version:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  def create_www_graph_networkit(n_nodes, m_edges, seed=42):
57
  """
58
- Create a realistic internet simulation using NetworKit - optimized for large graphs.
59
  """
60
  cache_key = (n_nodes, m_edges, seed)
61
 
@@ -66,98 +89,610 @@ def create_www_graph_networkit(n_nodes, m_edges, seed=42):
66
  # Set random seed for NetworKit
67
  nk.setSeed(seed, False)
68
 
69
- # For very large graphs, use different approach
70
- if n_nodes >= 500000:
71
- # Use R-MAT generator for very large graphs (faster)
72
- generator = nk.generators.RmatGenerator(
73
- scale=int(np.log2(n_nodes)),
74
- edgeFactor=m_edges,
75
- a=0.57, b=0.19, c=0.19, d=0.05
76
- )
77
- www_graph = generator.generate()
78
-
79
- # Convert to directed if needed
80
- if not www_graph.isDirected():
81
- directed_graph = nk.Graph(n=www_graph.numberOfNodes(), weighted=False, directed=True)
82
- for u, v in www_graph.iterEdges():
83
- directed_graph.addEdge(u, v)
84
- www_graph = directed_graph
85
- else:
86
- # Use BarabΓ‘si-Albert for smaller graphs
87
- generator = nk.generators.BarabasiAlbertGenerator(k=m_edges, nMax=n_nodes, n0=m_edges)
88
- www_graph = generator.generate()
89
-
90
- # Make it directed
91
- if not www_graph.isDirected():
92
- directed_graph = nk.Graph(n=www_graph.numberOfNodes(), weighted=False, directed=True)
93
- for u, v in www_graph.iterEdges():
94
- directed_graph.addEdge(u, v)
95
- directed_graph.addEdge(v, u) # Make bidirectional
96
- www_graph = directed_graph
97
 
98
  # Cache the result
99
  st.session_state.www_graph_cache = (cache_key, www_graph)
100
  return www_graph
101
 
102
- # 4. OPTIMIZE THE PAGERANK CALCULATION
103
- # Replace the PageRank section in process_configuration_networkit with:
 
104
 
105
- # Calculate PageRank using NetworKit with optimized settings for large graphs
106
- try:
107
- if total_nodes >= 500000:
108
- # Use more relaxed tolerance for very large graphs
109
- pagerank_algo = nk.centrality.PageRank(merged_graph, damp=0.85, tol=1e-4)
110
- else:
111
- pagerank_algo = nk.centrality.PageRank(merged_graph, damp=0.85, tol=1e-6)
 
112
 
113
- pagerank_algo.run()
114
- pagerank_values = pagerank_algo.scores()
 
115
 
116
- except Exception as e:
117
- st.warning(f"PageRank calculation failed: {e}. Using degree centrality instead.")
118
- # Fallback to degree centrality
119
- degree_algo = nk.centrality.DegreeCentrality(merged_graph, normalized=True)
120
- degree_algo.run()
121
- pagerank_values = degree_algo.scores()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- # 5. ADD MEMORY MANAGEMENT
124
- # Add this function and call it after each simulation:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- def cleanup_memory():
127
- """Clean up memory after large graph operations."""
128
- gc.collect() # Force garbage collection
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
- # Call this in run_single_simulation after processing:
131
- # ... existing simulation code ...
132
- cleanup_memory() # Add this line before returning results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- # 6. MODIFY THE PROGRESS MESSAGES FOR LARGE SIMULATIONS
135
- # Update the encouraging_messages list in main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- if www_nodes >= 500000:
138
- encouraging_messages = [
139
- f"πŸ”¬ Creating massive internet simulation ({www_nodes:,} sites)... This will take a while!",
140
- "🌐 Building ultra-large network topology...",
141
- "πŸ“Š Computing importance scores for massive network...",
142
- "🎯 Running test with millions of connections...",
143
- "πŸ“ˆ Almost there! Processing final calculations..."
144
- ]
145
- else:
146
- encouraging_messages = [
147
- f"πŸ”¬ Setting up large internet simulation ({www_nodes:,} sites)...",
148
- "🌐 Connecting your pages to the web...",
149
- "πŸ“Š Calculating page importance scores...",
150
- "🎯 Running tests with different scenarios...",
151
- "πŸ“ˆ Almost done! Analyzing results..."
152
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- # 7. ADD OPTION FOR REDUCED TESTS ON LARGE SIMULATIONS
155
- # Add this logic before the test running section:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
- # Automatically reduce tests for very large simulations
158
- if www_nodes >= 750000 and num_tests > 10:
159
- st.warning(f"⚠️ Automatically reducing tests from {num_tests} to 10 for {internet_size} to prevent timeout.")
160
- num_tests = min(num_tests, 10)
161
- elif www_nodes >= 500000 and num_tests > 15:
162
- st.warning(f"⚠️ Automatically reducing tests from {num_tests} to 15 for {internet_size}.")
163
- num_tests = min(num_tests, 15)
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import networkit as nk
5
+ import matplotlib.pyplot as plt
6
+ import seaborn as sns
7
+ import plotly.express as px
8
+ import plotly.graph_objects as go
9
+ from plotly.subplots import make_subplots
10
+ import time
11
+ import gc
12
+ from io import StringIO
13
+ import random
14
+ from collections import defaultdict
15
 
16
+ # Set page config
17
+ st.set_page_config(
18
+ page_title="Website Link Impact Analyzer",
19
+ page_icon="πŸ”—",
20
+ layout="wide",
21
+ initial_sidebar_state="expanded"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  )
23
 
24
+ # Global cache for WWW graph
25
+ if 'www_graph_cache' not in st.session_state:
26
+ st.session_state.www_graph_cache = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ def load_graph_from_csv_networkit(file_content, file_name):
29
+ """
30
+ Load page links from CSV file using NetworKit.
31
+ """
32
+ try:
33
+ # Read CSV content
34
+ df = pd.read_csv(StringIO(file_content))
35
+
36
+ # Check required columns with user-friendly names
37
+ required_cols = ['FROM', 'TO']
38
+ if not all(col in df.columns for col in required_cols):
39
+ st.error(f"""
40
+ ❌ **File Format Error**
41
+
42
+ Your CSV file needs these column names:
43
+ - **FROM** (the page that has the link)
44
+ - **TO** (the page being linked to)
45
+
46
+ Your file has: {', '.join(df.columns)}
47
+ """)
48
+ return None, None, None
49
+
50
+ # Clean data
51
+ df = df.dropna(subset=['FROM', 'TO'])
52
+ df['FROM'] = df['FROM'].astype(str)
53
+ df['TO'] = df['TO'].astype(str)
54
+
55
+ if len(df) == 0:
56
+ st.error(f"❌ No valid page links found in {file_name}")
57
+ return None, None, None
58
+
59
+ # Get unique nodes and create mapping
60
+ all_nodes = list(set(df['FROM'].tolist() + df['TO'].tolist()))
61
+ node_to_idx = {node: i for i, node in enumerate(all_nodes)}
62
+
63
+ # Create NetworKit graph
64
+ G = nk.Graph(n=len(all_nodes), weighted=False, directed=True)
65
+
66
+ # Add edges
67
+ for _, row in df.iterrows():
68
+ source_idx = node_to_idx[row['FROM']]
69
+ target_idx = node_to_idx[row['TO']]
70
+ G.addEdge(source_idx, target_idx)
71
+
72
+ return G, all_nodes, node_to_idx
73
+
74
+ except Exception as e:
75
+ st.error(f"❌ **Error reading file**: {str(e)}")
76
+ st.info("πŸ’‘ **Tip**: Make sure your file is a valid CSV with FROM and TO columns for page links")
77
+ return None, None, None
78
 
79
  def create_www_graph_networkit(n_nodes, m_edges, seed=42):
80
  """
81
+ Create a realistic internet simulation using NetworKit with BarabΓ‘si-Albert model.
82
  """
83
  cache_key = (n_nodes, m_edges, seed)
84
 
 
89
  # Set random seed for NetworKit
90
  nk.setSeed(seed, False)
91
 
92
+ # Always use BarabΓ‘si-Albert generator for realistic web structure
93
+ generator = nk.generators.BarabasiAlbertGenerator(k=m_edges, nMax=n_nodes, n0=m_edges)
94
+ www_graph = generator.generate()
95
+
96
+ # Make it directed
97
+ if not www_graph.isDirected():
98
+ directed_graph = nk.Graph(n=www_graph.numberOfNodes(), weighted=False, directed=True)
99
+ for u, v in www_graph.iterEdges():
100
+ directed_graph.addEdge(u, v)
101
+ directed_graph.addEdge(v, u) # Make bidirectional
102
+ www_graph = directed_graph
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  # Cache the result
105
  st.session_state.www_graph_cache = (cache_key, www_graph)
106
  return www_graph
107
 
108
+ def cleanup_memory():
109
+ """Clean up memory after large graph operations."""
110
+ gc.collect() # Force garbage collection
111
 
112
+ def process_configuration_networkit(www_graph, kalicube_graph, kalicube_nodes,
113
+ min_connections=5, max_connections=50):
114
+ """
115
+ Test how your page network performs in the real internet using NetworKit.
116
+ """
117
+ # Get WWW graph info
118
+ www_node_count = www_graph.numberOfNodes()
119
+ kalicube_node_count = len(kalicube_nodes)
120
 
121
+ # Create node mapping for kalicube nodes
122
+ kalicube_offset = www_node_count
123
+ kalicube_node_mapping = {}
124
 
125
+ for i, node in enumerate(kalicube_nodes):
126
+ new_node_id = kalicube_offset + i
127
+ kalicube_node_mapping[node] = new_node_id
128
+
129
+ # Create merged graph
130
+ total_nodes = www_node_count + kalicube_node_count
131
+ merged_graph = nk.Graph(n=total_nodes, weighted=False, directed=True)
132
+
133
+ # Add WWW edges
134
+ for u, v in www_graph.iterEdges():
135
+ merged_graph.addEdge(u, v)
136
+
137
+ # Add kalicube edges with new node IDs
138
+ kalicube_idx_to_node = {i: node for i, node in enumerate(kalicube_nodes)}
139
+
140
+ for u, v in kalicube_graph.iterEdges():
141
+ source_node = kalicube_idx_to_node[u]
142
+ target_node = kalicube_idx_to_node[v]
143
+ new_source_id = kalicube_node_mapping[source_node]
144
+ new_target_id = kalicube_node_mapping[target_node]
145
+ merged_graph.addEdge(new_source_id, new_target_id)
146
+
147
+ # Randomly connect kalicube pages to WWW
148
+ n_connections = min(min_connections, www_node_count, kalicube_node_count)
149
+
150
+ www_sample = random.sample(range(www_node_count), n_connections)
151
+ kalicube_sample = random.sample(list(kalicube_node_mapping.values()), n_connections)
152
+
153
+ for www_node, kalicube_node in zip(www_sample, kalicube_sample):
154
+ merged_graph.addEdge(www_node, kalicube_node)
155
+
156
+ # Calculate PageRank using NetworKit with optimized settings for large graphs
157
+ try:
158
+ if total_nodes >= 500000:
159
+ # Use more relaxed tolerance for very large graphs
160
+ pagerank_algo = nk.centrality.PageRank(merged_graph, damp=0.85, tol=1e-4)
161
+ else:
162
+ pagerank_algo = nk.centrality.PageRank(merged_graph, damp=0.85, tol=1e-6)
163
+
164
+ pagerank_algo.run()
165
+ pagerank_values = pagerank_algo.scores()
166
+
167
+ except Exception as e:
168
+ st.warning(f"PageRank calculation failed: {e}. Using degree centrality instead.")
169
+ # Fallback to degree centrality
170
+ degree_algo = nk.centrality.DegreeCentrality(merged_graph, normalized=True)
171
+ degree_algo.run()
172
+ pagerank_values = degree_algo.scores()
173
+
174
+ # Extract PageRank values for kalicube nodes
175
+ pagerank_dict = {}
176
+ for node, node_id in kalicube_node_mapping.items():
177
+ pagerank_dict[node] = pagerank_values[node_id] if node_id < len(pagerank_values) else 0.0
178
+
179
+ return pagerank_dict
180
 
181
+ def create_comparison_dataframe(pagerank_old_dict, pagerank_new_dict, simulation_id):
182
+ """
183
+ Compare before and after results.
184
+ """
185
+ # Find pages that appear in both tests
186
+ old_urls = set(pagerank_old_dict.keys())
187
+ new_urls = set(pagerank_new_dict.keys())
188
+ common_urls = old_urls & new_urls
189
+
190
+ if not common_urls:
191
+ return pd.DataFrame()
192
+
193
+ # Create comparison data
194
+ comparison_data = []
195
+
196
+ # Sort pages by importance for ranking
197
+ old_sorted = sorted(pagerank_old_dict.items(), key=lambda x: x[1], reverse=True)
198
+ new_sorted = sorted(pagerank_new_dict.items(), key=lambda x: x[1], reverse=True)
199
+
200
+ # Create ranking mappings
201
+ old_ranks = {url: rank + 1 for rank, (url, _) in enumerate(old_sorted)}
202
+ new_ranks = {url: rank + 1 for rank, (url, _) in enumerate(new_sorted)}
203
+
204
+ for url in common_urls:
205
+ importance_before = pagerank_old_dict[url]
206
+ importance_after = pagerank_new_dict[url]
207
+ rank_before = old_ranks[url]
208
+ rank_after = new_ranks[url]
209
+
210
+ importance_change = importance_after - importance_before
211
+ importance_change_pct = (importance_change / importance_before) * 100 if importance_before > 0 else 0
212
+ rank_change = rank_after - rank_before
213
+ rank_change_pct = (rank_change / rank_before) * 100 if rank_before > 0 else 0
214
+
215
+ comparison_data.append({
216
+ 'Page_URL': url,
217
+ 'Importance_Before': importance_before,
218
+ 'Importance_After': importance_after,
219
+ 'Rank_Before': rank_before,
220
+ 'Rank_After': rank_after,
221
+ 'Importance_Change': importance_change,
222
+ 'Importance_Change_%': importance_change_pct,
223
+ 'Rank_Change': rank_change,
224
+ 'Rank_Change_%': rank_change_pct,
225
+ 'Test_Number': simulation_id
226
+ })
227
+
228
+ return pd.DataFrame(comparison_data)
229
 
230
+ def run_single_simulation(simulation_id, kalicube_graph_old, kalicube_graph_new,
231
+ kalicube_nodes_old, kalicube_nodes_new,
232
+ www_nodes, www_edges, min_conn, max_conn):
233
+ """
234
+ Run one test comparing before and after.
235
+ """
236
+ sim_seed = 42 + simulation_id
237
+ random.seed(sim_seed)
238
+ np.random.seed(sim_seed)
239
+
240
+ # Create internet simulation
241
+ www_graph = create_www_graph_networkit(www_nodes, www_edges, sim_seed)
242
+
243
+ # Test original setup
244
+ importance_old_dict = process_configuration_networkit(
245
+ www_graph, kalicube_graph_old, kalicube_nodes_old, min_conn, max_conn
246
+ )
247
+
248
+ # Test new setup
249
+ importance_new_dict = process_configuration_networkit(
250
+ www_graph, kalicube_graph_new, kalicube_nodes_new, min_conn, max_conn
251
+ )
252
+
253
+ # Compare results
254
+ comparison_df = create_comparison_dataframe(
255
+ importance_old_dict, importance_new_dict, simulation_id
256
+ )
257
+
258
+ # Clean up memory after large operations
259
+ cleanup_memory()
260
 
261
+ if comparison_df.empty:
262
+ return None, None
263
+
264
+ # Calculate summary
265
+ total_before = comparison_df['Importance_Before'].sum()
266
+ total_after = comparison_df['Importance_After'].sum()
267
+ total_change = total_after - total_before
268
+ change_pct = (total_change / total_before) * 100 if total_before > 0 else 0
269
+
270
+ rank_changes = comparison_df['Rank_Change'].values
271
+ rank_improvements = np.sum(rank_changes < 0) # Lower rank number = better
272
+ rank_drops = np.sum(rank_changes > 0)
273
+ rank_unchanged = np.sum(rank_changes == 0)
274
+ avg_rank_change = np.mean(rank_changes)
275
+
276
+ result = {
277
+ 'Test_Number': simulation_id + 1,
278
+ 'Total_Before': total_before,
279
+ 'Total_After': total_after,
280
+ 'Total_Change': total_change,
281
+ 'Change_Percent': change_pct,
282
+ 'Pages_Improved': rank_improvements,
283
+ 'Pages_Dropped': rank_drops,
284
+ 'Pages_Unchanged': rank_unchanged,
285
+ 'Avg_Rank_Change': avg_rank_change
286
+ }
287
+
288
+ return result, comparison_df
289
 
290
+ def get_traffic_light_status(results_df, confidence_threshold=0.7):
291
+ """
292
+ Simple decision guidance based on test results.
293
+ """
294
+ total_tests = len(results_df)
295
+ positive_outcomes = (results_df['Total_Change'] > 0).sum()
296
+ negative_outcomes = (results_df['Total_Change'] < 0).sum()
297
+
298
+ positive_ratio = positive_outcomes / total_tests
299
+ negative_ratio = negative_outcomes / total_tests
300
+ mean_impact = results_df['Change_Percent'].mean()
301
+
302
+ # Simple traffic light logic
303
+ if positive_ratio >= confidence_threshold and mean_impact > 1.0:
304
+ return "🟒", "βœ… GO AHEAD - Your changes look great!", "go", "Most tests show good results. Your changes should help your page rankings."
305
+ elif positive_ratio >= confidence_threshold and mean_impact > 0:
306
+ return "🟑", "⚠️ PROCEED CAREFULLY - Small improvements expected", "caution", "Tests show some improvement, but it's modest. Consider if the effort is worth it."
307
+ elif negative_ratio >= confidence_threshold and mean_impact < -1.0:
308
+ return "πŸ”΄", "❌ STOP - Your changes may hurt your page rankings", "stop", "Most tests show negative results. Consider revising your changes before implementing."
309
+ elif negative_ratio >= confidence_threshold and mean_impact < 0:
310
+ return "🟑", "⚠️ PROCEED CAREFULLY - Some negative impact expected", "caution", "Tests show some negative impact. Monitor closely if you proceed."
311
+ else:
312
+ return "🟑", "🀷 MIXED RESULTS - Hard to predict", "caution", "Test results are mixed. Consider running more tests or getting expert advice."
313
 
314
+ def create_simple_visualizations(results_df, all_comparisons_df, confidence_threshold=0.7):
315
+ """
316
+ Create easy-to-understand visualizations.
317
+ """
318
+ # Traffic Light Assessment
319
+ traffic_emoji, traffic_status, traffic_level, explanation = get_traffic_light_status(results_df, confidence_threshold)
320
+
321
+ st.markdown("## 🚦 **Should You Make These Changes?**")
322
+
323
+ # Big, clear recommendation
324
+ if traffic_level == "go":
325
+ st.success(f"# {traffic_emoji}")
326
+ st.success(f"## {traffic_status}")
327
+ st.info(f"**Why:** {explanation}")
328
+ elif traffic_level == "stop":
329
+ st.error(f"# {traffic_emoji}")
330
+ st.error(f"## {traffic_status}")
331
+ st.warning(f"**Why:** {explanation}")
332
+ else:
333
+ st.warning(f"# {traffic_emoji}")
334
+ st.warning(f"## {traffic_status}")
335
+ st.info(f"**Why:** {explanation}")
336
+
337
+ # Simple metrics in plain English
338
+ st.markdown("### πŸ“Š **Test Results Summary**")
339
+ col1, col2, col3 = st.columns(3)
340
+
341
+ with col1:
342
+ positive_tests = (results_df['Total_Change'] > 0).sum()
343
+ total_tests = len(results_df)
344
+ st.metric("Tests Showing Improvement", f"{positive_tests} out of {total_tests}",
345
+ delta=f"{positive_tests/total_tests:.0%} positive")
346
+
347
+ with col2:
348
+ mean_change = results_df['Change_Percent'].mean()
349
+ st.metric("Average Impact on Rankings", f"{mean_change:.1f}%",
350
+ delta="Higher is better")
351
+
352
+ with col3:
353
+ improved_sites = results_df['Pages_Improved'].mean()
354
+ st.metric("Pages That Improved (avg)", f"{improved_sites:.0f}",
355
+ delta="per test")
356
 
357
+ def main():
358
+ st.title("πŸ”— Page Link Impact Analyzer (Powered by NetworKit)")
359
+ st.markdown("**Find out if your page link changes will help or hurt your search rankings**")
360
+
361
+ # Simple intro
362
+ st.info("""
363
+ πŸ‘‹ **Welcome!** This tool helps you test page link changes before you make them.
364
+
365
+ **What it does:** Simulates how your link changes might affect your page rankings in search engines.
366
+
367
+ **What you need:** Two CSV files - one with your current page links, one with your planned changes.
368
+
369
+ ⚑ **Now powered by NetworKit** - A high-performance network analysis toolkit for faster and more efficient analysis of large-scale networks!
370
+ """)
371
+
372
+ # Sidebar - simplified
373
+ st.sidebar.header("βš™οΈ Settings")
374
+
375
+ # File uploads with better guidance
376
+ st.sidebar.markdown("### πŸ“ **Step 1: Upload Your Files**")
377
+ st.sidebar.markdown("*Need help with file format? Check the 'File Format Help' section below.*")
378
+
379
+ old_file = st.sidebar.file_uploader("Current Page Links (CSV)", type=['csv'], key="old",
380
+ help="Upload a CSV file with your current page links")
381
+ new_file = st.sidebar.file_uploader("Planned Page Links (CSV)", type=['csv'], key="new",
382
+ help="Upload a CSV file with your planned page links")
383
+
384
+ # Simplified settings
385
+ st.sidebar.markdown("### 🎯 **Step 2: Test Settings**")
386
+
387
+ num_tests = st.sidebar.select_slider(
388
+ "How many tests to run?",
389
+ options=[5, 10, 15, 20, 25, 30],
390
+ value=10,
391
+ help="More tests = more reliable results, but takes longer"
392
+ )
393
+
394
+ internet_size = st.sidebar.select_slider(
395
+ "Internet simulation size",
396
+ options=[
397
+ "Large (100K sites)",
398
+ "Very Large (250K sites)",
399
+ "Huge (500K sites)",
400
+ "Massive (750K sites)",
401
+ "Ultra (1M sites)"
402
+ ],
403
+ value="Large (100K sites)",
404
+ help="Larger = more realistic but much slower. WARNING: 500K+ may take several minutes per test!"
405
+ )
406
+
407
+ # Convert internet size to numbers
408
+ size_map = {
409
+ "Large (100K sites)": 100000,
410
+ "Very Large (250K sites)": 250000,
411
+ "Huge (500K sites)": 500000,
412
+ "Massive (750K sites)": 750000,
413
+ "Ultra (1M sites)": 1000000
414
+ }
415
+ www_nodes = size_map[internet_size]
416
+
417
+ # Performance warnings
418
+ if www_nodes >= 500000:
419
+ st.sidebar.warning(f"""
420
+ ⚠️ **Performance Warning**:
421
+ {internet_size} will be very slow!
422
+ Expect 2-10 minutes per test.
423
+ Consider using fewer tests.
424
+ """)
425
+ elif www_nodes >= 250000:
426
+ st.sidebar.info(f"""
427
+ ℹ️ **Note**: {internet_size} may take
428
+ 30-60 seconds per test.
429
+ """)
430
+
431
+ # Advanced settings (hidden by default)
432
+ with st.sidebar.expander("πŸ”§ Advanced Settings (Optional)"):
433
+ confidence_level = st.slider("Confidence level for recommendations", 60, 90, 70, 5,
434
+ help="Higher = stricter requirements for green/red lights")
435
+ show_details = st.checkbox("Show detailed results", False)
436
+ auto_run = st.checkbox("Auto-run when files uploaded", False)
437
+
438
+ confidence_threshold = confidence_level / 100
439
+
440
+ # Main content
441
+ if old_file is not None and new_file is not None:
442
+ # Load files
443
+ old_content = old_file.getvalue().decode('utf-8')
444
+ new_content = new_file.getvalue().decode('utf-8')
445
+
446
+ # Show file status
447
+ col1, col2 = st.columns(2)
448
+ with col1:
449
+ st.success(f"βœ… **Current Page Links**: {old_file.name}")
450
+ with col2:
451
+ st.success(f"βœ… **Planned Page Links**: {new_file.name}")
452
+
453
+ # Load and validate files
454
+ with st.spinner("Reading your files..."):
455
+ kalicube_graph_old, kalicube_nodes_old, kalicube_url_mapping_old = \
456
+ load_graph_from_csv_networkit(old_content, old_file.name)
457
+
458
+ kalicube_graph_new, kalicube_nodes_new, kalicube_url_mapping_new = \
459
+ load_graph_from_csv_networkit(new_content, new_file.name)
460
+
461
+ if kalicube_graph_old is not None and kalicube_graph_new is not None:
462
+ # Show what we found
463
+ st.markdown("### πŸ“ˆ **What We Found in Your Files**")
464
+ info_col1, info_col2 = st.columns(2)
465
+
466
+ with info_col1:
467
+ st.info(f"""
468
+ **Current Setup:**
469
+ - {len(kalicube_nodes_old)} pages
470
+ - {kalicube_graph_old.numberOfEdges()} links between them
471
+ """)
472
+
473
+ with info_col2:
474
+ st.info(f"""
475
+ **Planned Setup:**
476
+ - {len(kalicube_nodes_new)} pages
477
+ - {kalicube_graph_new.numberOfEdges()} links between them
478
+ """)
479
+
480
+ # Big, obvious run button
481
+ st.markdown("### πŸš€ **Step 3: Run the Test**")
482
+
483
+ run_button = st.button("πŸ”¬ Test My Changes", type="primary", use_container_width=True)
484
+
485
+ if run_button or auto_run:
486
+ # Automatically reduce tests for very large simulations
487
+ if www_nodes >= 750000 and num_tests > 10:
488
+ st.warning(f"⚠️ Automatically reducing tests from {num_tests} to 10 for {internet_size} to prevent timeout.")
489
+ num_tests = min(num_tests, 10)
490
+ elif www_nodes >= 500000 and num_tests > 15:
491
+ st.warning(f"⚠️ Automatically reducing tests from {num_tests} to 15 for {internet_size}.")
492
+ num_tests = min(num_tests, 15)
493
+
494
+ # Progress with encouraging messages
495
+ progress_bar = st.progress(0)
496
+ status_text = st.empty()
497
+
498
+ # Dynamic messages based on simulation size
499
+ if www_nodes >= 500000:
500
+ encouraging_messages = [
501
+ f"πŸ”¬ Creating massive BarabΓ‘si-Albert simulation ({www_nodes:,} sites)... This will take a while!",
502
+ "🌐 Building scale-free network topology with preferential attachment...",
503
+ "οΏ½οΏ½οΏ½οΏ½ Computing PageRank scores for massive scale-free network...",
504
+ "🎯 Running test with millions of preferential connections...",
505
+ "πŸ“ˆ Almost there! Processing final calculations..."
506
+ ]
507
+ else:
508
+ encouraging_messages = [
509
+ f"πŸ”¬ Setting up BarabΓ‘si-Albert simulation ({www_nodes:,} sites)...",
510
+ "🌐 Creating scale-free network with preferential attachment...",
511
+ "πŸ“Š Calculating page importance scores...",
512
+ "🎯 Running tests with different scenarios...",
513
+ "πŸ“ˆ Almost done! Analyzing results..."
514
+ ]
515
+
516
+ all_results = []
517
+ all_comparisons = []
518
+
519
+ start_time = time.time()
520
+
521
+ # Run tests with encouragement
522
+ for i in range(num_tests):
523
+ msg_idx = min(i // max(1, num_tests // len(encouraging_messages)), len(encouraging_messages) - 1)
524
+ status_text.text(f"{encouraging_messages[msg_idx]} (Test {i+1}/{num_tests})")
525
+ progress_bar.progress((i + 1) / num_tests)
526
+
527
+ result, comparison_df = run_single_simulation(
528
+ i, kalicube_graph_old, kalicube_graph_new,
529
+ kalicube_nodes_old, kalicube_nodes_new,
530
+ www_nodes, 2, 5, 25 # simplified parameters
531
+ )
532
+
533
+ if result is not None:
534
+ all_results.append(result)
535
+ all_comparisons.append(comparison_df)
536
+
537
+ end_time = time.time()
538
+
539
+ # Clear progress
540
+ progress_bar.empty()
541
+ status_text.empty()
542
+
543
+ if all_results:
544
+ results_df = pd.DataFrame(all_results)
545
+ all_comparisons_df = pd.concat(all_comparisons, ignore_index=True) if all_comparisons else pd.DataFrame()
546
+
547
+ # Show results
548
+ st.success(f"πŸŽ‰ **Test Complete!** Ran {len(all_results)} tests in {end_time - start_time:.0f} seconds")
549
+
550
+ # Create simple visualizations
551
+ create_simple_visualizations(results_df, all_comparisons_df, confidence_threshold)
552
+
553
+ # Download section
554
+ st.markdown("### πŸ’Ύ **Save Your Results**")
555
+ col1, col2 = st.columns(2)
556
+
557
+ with col1:
558
+ csv_summary = results_df.to_csv(index=False)
559
+ st.download_button(
560
+ label="πŸ“Š Download Summary Report",
561
+ data=csv_summary,
562
+ file_name=f"website_impact_summary_{int(time.time())}.csv",
563
+ mime="text/csv"
564
+ )
565
+
566
+ with col2:
567
+ if not all_comparisons_df.empty:
568
+ csv_detailed = all_comparisons_df.to_csv(index=False)
569
+ st.download_button(
570
+ label="πŸ“‹ Download Detailed Results",
571
+ data=csv_detailed,
572
+ file_name=f"website_impact_detailed_{int(time.time())}.csv",
573
+ mime="text/csv"
574
+ )
575
+
576
+ # Show detailed results if requested
577
+ if show_details and not all_comparisons_df.empty:
578
+ st.markdown("### πŸ” **Detailed Results** (For the curious)")
579
+
580
+ # Simple filter
581
+ st.markdown("**Filter results:**")
582
+ filter_col1, filter_col2 = st.columns(2)
583
+ with filter_col1:
584
+ min_change = st.number_input("Show changes above (%)",
585
+ value=float(all_comparisons_df['Importance_Change_%'].min()),
586
+ step=0.1)
587
+
588
+ # Apply filter and show
589
+ filtered_df = all_comparisons_df[all_comparisons_df['Importance_Change_%'] >= min_change]
590
+
591
+ # Rename columns for clarity
592
+ display_df = filtered_df.copy()
593
+ display_df = display_df.rename(columns={
594
+ 'Page_URL': 'Page URL',
595
+ 'Importance_Change_%': 'Impact (%)',
596
+ 'Rank_Change': 'Rank Change',
597
+ 'Test_Number': 'Test #'
598
+ })
599
+
600
+ st.dataframe(
601
+ display_df[['Page URL', 'Impact (%)', 'Rank_Change', 'Test #']].sort_values('Impact (%)', ascending=False),
602
+ use_container_width=True,
603
+ height=300
604
+ )
605
+
606
+ else:
607
+ st.error("❌ No test results generated. Please check your files and try again.")
608
+
609
+ else:
610
+ # Help section when no files uploaded
611
+ st.markdown("---")
612
+
613
+ # File format help
614
+ with st.expander("πŸ“‹ **File Format Help** - How to prepare your CSV files"):
615
+ st.markdown("""
616
+ ### βœ… **Correct Format**
617
+ Your CSV files need exactly these column names:
618
+ - **FROM** = the page that has the link
619
+ - **TO** = the page being linked to
620
+
621
+ ### πŸ“ **Example:**
622
+ ```
623
+ FROM,TO
624
+ mysite.com/about,mysite.com/contact
625
+ mysite.com/blog/post1,partner.com/resource
626
+ partner.com/page,mysite.com/services
627
+ ```
628
+
629
+ ### πŸ’‘ **Tips:**
630
+ - Use any spreadsheet program (Excel, Google Sheets) to create these
631
+ - Save as CSV format
632
+ - Include full URLs or page paths
633
+ - Make sure page URLs are consistent (mysite.com/page vs mysite.com/page/ are different!)
634
+ - Each row represents one link from one page to another
635
+ """)
636
+
637
+ with st.expander("πŸ€” **What This Tool Actually Does** - Explained Simply"):
638
+ st.markdown("""
639
+ ### 🌐 **The Big Picture**
640
+ When you change links between your pages, it affects how search engines see your site. But it's hard to predict the exact impact because the internet is huge and constantly changing.
641
+
642
+ ### πŸ§ͺ **Our Solution: Virtual Testing**
643
+ 1. **We simulate the internet** - Create a virtual version with hundreds of thousands or millions of pages
644
+ 2. **We test your changes** - Run your current page links vs. your planned links
645
+ 3. **We repeat many times** - Each test uses slightly different internet conditions
646
+ 4. **We analyze the pattern** - Look at whether your changes usually help or hurt
647
+
648
+ ### 🚦 **The Traffic Light System**
649
+ - **🟒 Green = Go ahead** - Most tests show your changes help
650
+ - **🟑 Yellow = Be careful** - Mixed results or small impact
651
+ - **πŸ”΄ Red = Stop** - Most tests show your changes hurt
652
+
653
+ ### 🎯 **Why This Works**
654
+ Instead of guessing, you get data-driven confidence about your page link changes!
655
+
656
+ ### ⚑ **Powered by NetworKit**
657
+ This version uses NetworKit, a high-performance network analysis toolkit that's much faster than traditional tools for analyzing large networks. It can now handle simulations of 100K to 1M sites!
658
+
659
+ ### πŸ”¬ **Large-Scale Simulations**
660
+ - **100K sites**: ~10-30 seconds per test
661
+ - **250K sites**: ~30-60 seconds per test
662
+ - **500K sites**: ~1-3 minutes per test
663
+ - **750K sites**: ~2-5 minutes per test
664
+ - **1M sites**: ~3-10 minutes per test
665
+ """)
666
+
667
+ with st.expander("❓ **Common Questions**"):
668
+ st.markdown("""
669
+ **Q: How accurate is this?**
670
+ A: The tool shows trends and probabilities, not exact predictions. It's like weather forecasting - very useful for planning!
671
+
672
+ **Q: How long does it take?**
673
+ A: From 30 seconds to 10 minutes per test, depending on simulation size. NetworKit makes it much faster than before!
674
+
675
+ **Q: What if I get yellow results?**
676
+ A: Yellow means proceed carefully. Consider running more tests, getting expert advice, or monitoring closely if you implement.
677
+
678
+ **Q: Can I test multiple scenarios?**
679
+ A: Yes! Just upload different "planned changes" files to compare options.
680
+
681
+ **Q: What file size limits?**
682
+ A: Works best with up to 50,000 page links. Larger files may be slow.
683
+
684
+ **Q: What's the difference between pages and websites?**
685
+ A: Pages are specific URLs (like mysite.com/about), while websites are domains (like mysite.com). This tool analyzes individual page links.
686
+
687
+ **Q: What's NetworKit?**
688
+ A: NetworKit is a high-performance network analysis toolkit with optimized C++ algorithms that makes calculations much faster and can handle larger datasets more efficiently.
689
+
690
+ **Q: Which simulation size should I choose?**
691
+ A: Start with 100K for testing. Use 250K-500K for realistic results. Only use 750K+ if you have time and want maximum realism.
692
+
693
+ **Q: Why does it take longer with bigger simulations?**
694
+ A: Larger simulations are more realistic but require more computation. The tool automatically adjusts algorithms for efficiency at different scales.
695
+ """)
696
 
697
+ if __name__ == "__main__":
698
+ main()