Spaces:
Sleeping
Sleeping
File size: 13,658 Bytes
5c05d7a 2f36052 5c05d7a 2f36052 5c05d7a 2f36052 5c05d7a e6abf6e 5c05d7a e6abf6e 5c05d7a 9e2bc99 5c05d7a 2f36052 a46a8e7 05d82ce dd5783d 5c05d7a a46a8e7 79dc41f a46a8e7 e830460 5240604 a46a8e7 5240604 a46a8e7 8a03bb3 a46a8e7 2932f79 a46a8e7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
import pandas as pd
import networkx as nx
import plotly.graph_objects as go
import gradio as gr
import re
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Load and preprocess the dataset
file_path = "cbinsights_data.csv" # Replace with your actual file path
try:
data = pd.read_csv(file_path, skiprows=1)
logger.info("CSV file loaded successfully.")
except FileNotFoundError:
logger.error(f"File not found: {file_path}")
raise
except Exception as e:
logger.error(f"Error loading CSV file: {e}")
raise
# Standardize column names
data.columns = data.columns.str.strip().str.lower()
logger.info(f"Standardized Column Names: {data.columns.tolist()}")
# Filter out Health since Healthcare is the correct Market Segment
data = data[data.industry != 'Health']
# Identify the valuation column
valuation_columns = [col for col in data.columns if 'valuation' in col.lower()]
if len(valuation_columns) != 1:
logger.error("Unable to identify a single valuation column.")
raise ValueError("Dataset should contain exactly one column with 'valuation' in its name.")
valuation_column = valuation_columns[0]
logger.info(f"Using valuation column: {valuation_column}")
# Clean and prepare data
data["Valuation_Billions"] = data[valuation_column].replace({'\$': '', ',': ''}, regex=True)
data["Valuation_Billions"] = pd.to_numeric(data["Valuation_Billions"], errors='coerce')
data = data.apply(lambda col: col.str.strip() if col.dtype == "object" else col)
data.rename(columns={
"company": "Company",
"date_joined": "Date_Joined",
"country": "Country",
"city": "City",
"industry": "Industry",
"select_investors": "Select_Investors"
}, inplace=True)
logger.info("Data cleaned and columns renamed.")
# Build investor-company mapping
def build_investor_company_mapping(df):
mapping = {}
for _, row in df.iterrows():
company = row["Company"]
investors = row["Select_Investors"]
if pd.notnull(investors):
for investor in investors.split(","):
investor = investor.strip()
if investor:
mapping.setdefault(investor, []).append(company)
return mapping
investor_company_mapping = build_investor_company_mapping(data)
logger.info("Investor to company mapping created.")
# -------------------------
# Valuation-Range Logic
# -------------------------
def filter_by_valuation_range(df, selected_valuation_range):
"""Filter dataframe by the specified valuation range in billions."""
if selected_valuation_range == "All":
return df # No further filtering
if selected_valuation_range == "1-5":
return df[(df["Valuation_Billions"] >= 1) & (df["Valuation_Billions"] < 5)]
elif selected_valuation_range == "5-10":
return df[(df["Valuation_Billions"] >= 5) & (df["Valuation_Billions"] < 10)]
elif selected_valuation_range == "10-15":
return df[(df["Valuation_Billions"] >= 10) & (df["Valuation_Billions"] < 15)]
elif selected_valuation_range == "15-20":
return df[(df["Valuation_Billions"] >= 15) & (df["Valuation_Billions"] < 20)]
elif selected_valuation_range == "20+":
return df[df["Valuation_Billions"] >= 20]
else:
return df # Fallback, should never happen
# Filter investors by country, industry, investor selection, company selection, and valuation range
def filter_investors(
selected_country,
selected_industry,
selected_investors,
selected_company,
exclude_countries,
exclude_industries,
exclude_companies,
exclude_investors,
selected_valuation_range
):
filtered_data = data.copy()
# 1) Valuation range filter
filtered_data = filter_by_valuation_range(filtered_data, selected_valuation_range)
# 2) Now apply the existing filters:
# Inclusion filters
if selected_country != "All":
filtered_data = filtered_data[filtered_data["Country"] == selected_country]
if selected_industry != "All":
filtered_data = filtered_data[filtered_data["Industry"] == selected_industry]
if selected_company != "All":
filtered_data = filtered_data[filtered_data["Company"] == selected_company]
if selected_investors:
pattern = '|'.join([re.escape(inv) for inv in selected_investors])
filtered_data = filtered_data[filtered_data["Select_Investors"].str.contains(pattern, na=False)]
# Exclusion filters
if exclude_countries:
filtered_data = filtered_data[~filtered_data["Country"].isin(exclude_countries)]
if exclude_industries:
filtered_data = filtered_data[~filtered_data["Industry"].isin(exclude_industries)]
if exclude_companies:
filtered_data = filtered_data[~filtered_data["Company"].isin(exclude_companies)]
if exclude_investors:
pattern = '|'.join([re.escape(inv) for inv in exclude_investors])
filtered_data = filtered_data[~filtered_data["Select_Investors"].str.contains(pattern, na=False)]
investor_company_mapping_filtered = build_investor_company_mapping(filtered_data)
filtered_investors = list(investor_company_mapping_filtered.keys())
return filtered_investors, filtered_data
# Generate Plotly graph
# NEW: We add selected_valuation_range so we can check if the user selected 15-20 or 20+
def generate_graph(investors, filtered_data, selected_valuation_range):
if not investors:
logger.warning("No investors selected.")
return go.Figure()
# Create a color map for investors
unique_investors = investors
num_colors = len(unique_investors)
color_palette = [
"#377eb8", "#e41a1c", "#4daf4a", "#984ea3",
"#ff7f00", "#ffff33", "#a65628", "#f781bf", "#999999"
]
while num_colors > len(color_palette):
color_palette.extend(color_palette)
investor_color_map = {investor: color_palette[i] for i, investor in enumerate(unique_investors)}
G = nx.Graph()
for investor in investors:
companies = filtered_data[filtered_data["Select_Investors"].str.contains(re.escape(investor), na=False)]["Company"].tolist()
for company in companies:
G.add_node(company)
G.add_node(investor)
G.add_edge(investor, company)
pos = nx.spring_layout(G, seed=1721, iterations=150)
edge_x, edge_y = [], []
for edge in G.edges():
x0, y0 = pos[edge[0]]
x1, y1 = pos[edge[1]]
edge_x.extend([x0, x1, None])
edge_y.extend([y0, y1, None])
edge_trace = go.Scatter(
x=edge_x,
y=edge_y,
line=dict(width=0.5, color='#aaaaaa'),
hoverinfo='none',
mode='lines'
)
node_x, node_y, node_text, node_textposition = [], [], [], []
node_color, node_size, node_hovertext = [], [], []
for node in G.nodes():
x, y = pos[node]
node_x.append(x)
node_y.append(y)
if node in investors:
node_text.append(node) # Add investor labels
node_color.append(investor_color_map[node])
node_size.append(30)
node_hovertext.append(f"Investor: {node}")
node_textposition.append('top center')
else:
valuation = filtered_data.loc[filtered_data["Company"] == node, "Valuation_Billions"].values
industry = filtered_data.loc[filtered_data["Company"] == node, "Industry"].values
size = valuation[0] * 5 if len(valuation) > 0 and not pd.isnull(valuation[0]) else 15
node_size.append(max(size, 10))
node_color.append("#a6d854")
# Build the hover label text
hovertext = f"Company: {node}"
if len(industry) > 0 and not pd.isnull(industry[0]):
hovertext += f"<br>Industry: {industry[0]}"
if len(valuation) > 0 and not pd.isnull(valuation[0]):
hovertext += f"<br>Valuation: ${valuation[0]:.2f}B"
node_hovertext.append(hovertext)
# NEW: If valuation range is 15–20 or 20+, show hovertext for all companies
if selected_valuation_range in ["15-20", "20+"]:
node_text.append(hovertext) # show full text
node_textposition.append('bottom center')
else:
# Old logic: only show the company name in certain conditions
if (
(len(valuation) > 0 and valuation[0] is not None and valuation[0] > 10) # Check if > 10B
or (len(filtered_data) < 15)
or (node in filtered_data.nlargest(5, "Valuation_Billions")["Company"].tolist())
):
node_text.append(node) # Show just the company name
node_textposition.append('bottom center')
else:
node_text.append("") # Hide company label
node_textposition.append('bottom center')
node_trace = go.Scatter(
x=node_x,
y=node_y,
text=node_text,
textposition=node_textposition,
mode='markers+text',
hoverinfo='text',
hovertext=node_hovertext,
textfont=dict(size=13), # Adjust label font size
marker=dict(
showscale=False,
size=node_size,
color=node_color,
line=dict(width=0.5, color='#333333')
)
)
# Compute total market cap
total_market_cap = filtered_data["Valuation_Billions"].sum()
fig = go.Figure(data=[edge_trace, node_trace])
fig.update_layout(
title="",
titlefont_size=28,
margin=dict(l=20, r=20, t=60, b=20),
hovermode='closest',
width=1200,
height=800,
autosize=True,
xaxis=dict(showgrid=False, zeroline=False, visible=False),
yaxis=dict(showgrid=False, zeroline=False, visible=False),
showlegend=False, # Hide the legend to maximize space
annotations=[
dict(
x=0.5, y=1.1, xref='paper', yref='paper',
text=f"Combined Market Cap: ${total_market_cap:.1f} Billions",
showarrow=False, font=dict(size=14), xanchor='center'
)
]
)
return fig
# Gradio app function
def app(
selected_country,
selected_industry,
selected_company,
selected_investors,
exclude_countries,
exclude_industries,
exclude_companies,
exclude_investors,
selected_valuation_range
):
investors, filtered_data = filter_investors(
selected_country,
selected_industry,
selected_investors,
selected_company,
exclude_countries,
exclude_industries,
exclude_companies,
exclude_investors,
selected_valuation_range
)
if not investors:
return go.Figure()
# NEW: Pass valuation_range to generate_graph
graph = generate_graph(investors, filtered_data, selected_valuation_range)
return graph
def main():
country_list = ["All"] + sorted(data["Country"].dropna().unique())
industry_list = ["All"] + sorted(data["Industry"].dropna().unique())
company_list = ["All"] + sorted(data["Company"].dropna().unique())
investor_list = sorted(investor_company_mapping.keys())
# Valuation range choices
valuation_ranges = ["All", "1-5", "5-10", "10-15", "15-20", "20+"]
with gr.Blocks(title="Venture Networks Visualization") as demo:
gr.Markdown("# Venture Networks Visualization")
with gr.Row():
country_filter = gr.Dropdown(choices=country_list, label="Country", value="All")
industry_filter = gr.Dropdown(choices=industry_list, label="Industry", value="All")
company_filter = gr.Dropdown(choices=company_list, label="Company", value="All")
investor_filter = gr.Dropdown(choices=investor_list, label="Select Investors", value=[], multiselect=True)
with gr.Row():
valuation_range_filter = gr.Dropdown(
choices=valuation_ranges,
label="Valuation Range (Billions)",
value="All"
)
exclude_country_filter = gr.Dropdown(choices=country_list[1:], label="Exclude Country", value=[], multiselect=True)
exclude_industry_filter = gr.Dropdown(choices=industry_list[1:], label="Exclude Industry", value=[], multiselect=True)
exclude_company_filter = gr.Dropdown(choices=company_list[1:], label="Exclude Company", value=[], multiselect=True)
exclude_investor_filter = gr.Dropdown(choices=investor_list, label="Exclude Investors", value=[], multiselect=True)
graph_output = gr.Plot(label="Network Graph")
inputs = [
country_filter,
industry_filter,
company_filter,
investor_filter,
exclude_country_filter,
exclude_industry_filter,
exclude_company_filter,
exclude_investor_filter,
valuation_range_filter
]
outputs = [graph_output]
# Set up event triggers for all inputs
for input_control in inputs:
input_control.change(app, inputs, outputs)
gr.Markdown("**Instructions:** Use the dropdowns to filter the network graph. For valuation ranges 15–20 or 20+, you’ll see each company's info label without hovering.")
gr.Markdown("**Note:** All companies are in green, while venture firms have different colors. The diameter of the company circle varies proportionate to the valuation.")
demo.launch()
if __name__ == "__main__":
main() |