import gradio as gr import pandas as pd import networkx as nx from pyvis.network import Network import tempfile import os import plotly.graph_objects as go def clean_time_column(df, time_col): # Try converting to integer (years) first try: df[time_col] = pd.to_numeric(df[time_col]).astype(int) return df, True except: # Fallback to string-based categorical if not purely numeric df[time_col] = df[time_col].astype(str) return df, False def generate_vis_html(df_filtered): nodes = set(df_filtered['Source'].unique()).union(set(df_filtered['Target'].unique())) net = Network( height="500px", width="100%", bgcolor="#16100c", font_color="#f4eee6", notebook=False ) net.set_options(""" var options = { "nodes": { "borderWidth": 2, "color": { "border": "#2c1e16", "background": "#ff7043", "highlight": { "border": "#ff7043", "background": "#ffffff" } }, "font": { "color": "#f4eee6", "size": 14, "face": "Inter, sans-serif" } }, "edges": { "color": { "color": "rgba(255, 112, 67, 0.4)", "highlight": "#ff7043" }, "smooth": { "type": "continuous" } }, "physics": { "barnesHut": { "gravitationalConstant": -12000, "centralGravity": 0.3, "springLength": 120, "springConstant": 0.04 } } } """) # Scale nodes by degree inside the filtered slice G = nx.from_pandas_edgelist(df_filtered, 'Source', 'Target', edge_attr='Weight' if 'Weight' in df_filtered.columns else None) degrees = dict(G.degree()) for node in nodes: deg = degrees.get(node, 1) net.add_node(node, label=node, size=10 + (deg * 2), title=f"Connection count: {deg}") for _, row in df_filtered.iterrows(): weight = row.get('Weight', 1.0) try: w_val = float(weight) if pd.isna(w_val): w_val = 1.0 except: w_val = 1.0 net.add_edge(row['Source'], row['Target'], value=w_val) temp_dir = tempfile.gettempdir() temp_path = os.path.join(temp_dir, next(tempfile._get_candidate_names()) + ".html") net.save_graph(temp_path) with open(temp_path, "r", encoding="utf-8") as f: html_content = f.read() try: os.remove(temp_path) except: pass escaped_html = html_content.replace('"', '"') iframe_code = f'' return iframe_code def analyze_dynamic_network(file_obj, min_val, max_val, cat_val, is_cumulative): if file_obj is None: return "Please upload a CSV or Excel file.", None, None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) try: if file_obj.name.endswith('.csv'): df = pd.read_csv(file_obj.name) else: df = pd.read_excel(file_obj.name) except Exception as e: return f"Error reading file: {str(e)}", None, None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) # Standardize headers rename_map = {} for col in df.columns: if col.lower() in ['source', 'from', 'node1']: rename_map[col] = 'Source' elif col.lower() in ['target', 'to', 'node2']: rename_map[col] = 'Target' elif col.lower() in ['weight', 'value', 'strength']: rename_map[col] = 'Weight' elif col.lower() in ['time', 'year', 'timestamp', 'date', 'interval']: rename_map[col] = 'Time' df = df.rename(columns=rename_map) if 'Source' not in df.columns or 'Target' not in df.columns or 'Time' not in df.columns: return "CSV/Excel must contain 'Source', 'Target', and a temporal column ('Time', 'Year', etc.).", None, None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) if 'Weight' not in df.columns: df['Weight'] = 1.0 df, is_numeric = clean_time_column(df, 'Time') # Filter operations if is_numeric: if is_cumulative: df_filtered = df[df['Time'] <= max_val] else: df_filtered = df[(df['Time'] >= min_val) & (df['Time'] <= max_val)] else: # Categorical slice if is_cumulative: # Cumulative categorical doesn't follow strict ordering, but we slice up to the selected value in sorting order unique_cats = sorted(df['Time'].unique()) idx = unique_cats.index(cat_val) + 1 if cat_val in unique_cats else len(unique_cats) df_filtered = df[df['Time'].isin(unique_cats[:idx])] else: df_filtered = df[df['Time'] == cat_val] if df_filtered.empty: return "No network links found inside this specific timeframe.", None, None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) # Calculate global stats vs time to plot evolution stats_data = [] if is_numeric: unique_times = sorted(df['Time'].unique()) for t in unique_times: if is_cumulative: sub_df = df[df['Time'] <= t] else: sub_df = df[df['Time'] == t] sub_G = nx.from_pandas_edgelist(sub_df, 'Source', 'Target') stats_data.append({ "Time": t, "Nodes": sub_G.number_of_nodes(), "Edges": sub_G.number_of_edges(), "Density": nx.density(sub_G) }) else: unique_times = sorted(df['Time'].unique()) for idx, t in enumerate(unique_times): if is_cumulative: sub_df = df[df['Time'].isin(unique_times[:idx+1])] else: sub_df = df[df['Time'] == t] sub_G = nx.from_pandas_edgelist(sub_df, 'Source', 'Target') stats_data.append({ "Time": t, "Nodes": sub_G.number_of_nodes(), "Edges": sub_G.number_of_edges(), "Density": nx.density(sub_G) }) stats_df = pd.DataFrame(stats_data) # Generate Plotly trend line chart fig = go.Figure() fig.add_trace(go.Scatter(x=stats_df['Time'], y=stats_df['Nodes'], mode='lines+markers', name='Nodes', line=dict(color='#ff7043', width=3))) fig.add_trace(go.Scatter(x=stats_df['Time'], y=stats_df['Edges'], mode='lines+markers', name='Edges', line=dict(color='#ffffff', width=2))) fig.update_layout( title="Temporal Network Growth", paper_bgcolor='#16100c', plot_bgcolor='#16100c', font_color='#f4eee6', margin=dict(l=40, r=40, t=50, b=40), xaxis=dict(gridcolor='rgba(255,255,255,0.05)'), yaxis=dict(gridcolor='rgba(255,255,255,0.05)') ) # Current stats block G_curr = nx.from_pandas_edgelist(df_filtered, 'Source', 'Target') stats_html = f"""