Spaces:
Sleeping
Sleeping
Sync from GitHub main β ERP priority, WMCA/Shropshire watchlist, network preserve-owners fix (a7395ea)
a87217c verified Download network_loader.py from mipwr-admin/curium-intel: direct link, hf CLI and curl.
- Browser
- Download file 47 kB
-
https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/network_loader.py
- Command line
-
hf download hf://spaces/mipwr-admin/curium-intel/network_loader.py
-
curl -L -o network_loader.py https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/network_loader.py
47 kB
"""
Network Loader Module (network_loader.py)
Loads LinkedIn Connection Data CSV with movement tracking.
Expected CSV Columns:
- Owner: Colleague who owns the connection (e.g., 'Adam', 'Adela')
- Full Name: Contact's full name
- Company: Current company
- Position: Current position/title
- New Company?: 'Y' or 'N' - indicates if contact moved companies
- New Position?: 'Y' or 'N' - indicates if contact changed roles
- Date Connected: When the connection was made (optional)
Usage:
python network_loader.py # Load CSV
python network_loader.py --file custom.csv # Load custom file
python network_loader.py --match "Premier Foods" # Find connections
python network_loader.py --movers # Show movers alert
python network_loader.py --stats # Network statistics
"""
import os
import csv
import sqlite3
import re
from datetime import datetime
from typing import Optional
from dataclasses import dataclass
from enum import Enum
# Try to import fuzzy matching
try:
from rapidfuzz import fuzz, process
FUZZY_AVAILABLE = True
except ImportError:
FUZZY_AVAILABLE = False
print("Warning: rapidfuzz not installed. Install with: pip install rapidfuzz")
DATABASE = "leads.db"
DEFAULT_CSV_FILE = "data/my_team_connections.csv"
def convert_xlsx_to_csv(xlsx_path: str) -> str:
"""Convert an XLSX file to CSV format, returning the CSV path.
The team's master workbook contains many sheets (pivot tables, dropdowns,
message templates, etc.). `wb.active` returns whichever sheet was active
when the file was last saved β often *not* the data sheet. Instead, scan
every sheet, find those whose first ~15 rows contain the connection-data
header signature (Company + Position, plus either Owner/Full Name or
First Name + Last Name), and pick the largest match. Falls back to
`wb.active` if nothing looks like data.
"""
import openpyxl
csv_path = xlsx_path.rsplit('.', 1)[0] + '.csv'
wb = openpyxl.load_workbook(xlsx_path, read_only=True, data_only=True)
REQUIRED_TOKENS = {"company", "position"}
NAME_TOKENS = {"full name", "first name", "last name", "owner", "name"}
MOVEMENT_TOKENS = {"position change?", "company change?", "new position?", "new company?"}
def _sheet_score(ws) -> tuple[int, int, int] | None:
"""Return (priority, header_row_idx, n_rows) if sheet looks like
connection data; None otherwise. Higher priority = preferred.
Priority tiers (most preferred last):
0 β connection data, no Owner
1 β connection data with Owner
2 β connection data with Owner AND movement tracking
(Position Change? / Company Change?). The team's "New Data"
sheet has these and drives MOVERS/PROMOTED signals.
"""
try:
for header_idx, row in enumerate(ws.iter_rows(values_only=True, max_row=15)):
cells = {str(c).strip().lower() for c in row if c is not None}
if REQUIRED_TOKENS.issubset(cells) and (cells & NAME_TOKENS):
has_owner = "owner" in cells
has_movement = bool(cells & MOVEMENT_TOKENS)
if has_owner and has_movement:
priority = 2
elif has_owner:
priority = 1
else:
priority = 0
return (priority, header_idx, ws.max_row or 0)
except Exception:
return None
return None
best = None # (priority, n_rows, header_idx, sheet_name)
for sn in wb.sheetnames:
ws = wb[sn]
info = _sheet_score(ws)
if info is None:
continue
priority, header_idx, n_rows = info
candidate = (priority, n_rows, header_idx, sn)
if best is None or candidate > best:
best = candidate
if best is not None:
_, _, header_idx, sheet_name = best
ws = wb[sheet_name]
with open(csv_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
for i, row in enumerate(ws.iter_rows(values_only=True)):
if i < header_idx:
continue # skip preamble before header row
writer.writerow([cell if cell is not None else '' for cell in row])
else:
# Fallback: dump active sheet as before
ws = wb.active
with open(csv_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
for row in ws.iter_rows(values_only=True):
writer.writerow([cell if cell is not None else '' for cell in row])
wb.close()
return csv_path
# =============================================================================
# DATA MODELS
# =============================================================================
class ConnectionTier(Enum):
"""Connection strength tiers."""
TIER_1_EXACT_ROLE = 1 # Direct connection to target role
TIER_2_SENIOR = 2 # C-Suite/Director level connection
TIER_3_COMPANY = 3 # Any connection at company
NO_CONNECTION = 99 # No connection found
class ContactStatus(Enum):
"""Contact status flags."""
ACTIVE = "ACTIVE"
MOVER = "MOVER" # Changed companies
PROMOTED = "PROMOTED" # New position at same company
@dataclass
class ConnectionMatch:
"""Represents a matched connection."""
name: str
company: str
position: str
colleague: str
tier: ConnectionTier
match_score: float
is_senior: bool
is_mover: bool = False
role_match_score: float = 0.0
@property
def tier_emoji(self) -> str:
return {
ConnectionTier.TIER_1_EXACT_ROLE: "π―",
ConnectionTier.TIER_2_SENIOR: "β",
ConnectionTier.TIER_3_COMPANY: "π",
ConnectionTier.NO_CONNECTION: "βοΈ"
}.get(self.tier, "")
@property
def tier_label(self) -> str:
return {
ConnectionTier.TIER_1_EXACT_ROLE: "DIRECT HIT",
ConnectionTier.TIER_2_SENIOR: "SENIOR CONNECTION",
ConnectionTier.TIER_3_COMPANY: "COMPANY CONNECTION",
ConnectionTier.NO_CONNECTION: "NO CONNECTION"
}.get(self.tier, "")
@dataclass
class NetworkHit:
"""Represents a network intelligence result."""
company: str
target_role: Optional[str]
matches: list[ConnectionMatch]
best_match: Optional[ConnectionMatch]
tier: ConnectionTier
total_connections: int
@property
def has_connection(self) -> bool:
return self.tier != ConnectionTier.NO_CONNECTION
@property
def summary(self) -> str:
if not self.has_connection:
return f"βοΈ No connections found at {self.company}"
if self.best_match:
bm = self.best_match
mover_flag = " π MOVER" if bm.is_mover else ""
if self.tier == ConnectionTier.TIER_1_EXACT_ROLE:
return f"π― DIRECT HIT: {bm.colleague} knows {bm.name} ({bm.position}) at {self.company}!{mover_flag}"
elif self.tier == ConnectionTier.TIER_2_SENIOR:
return f"β SENIOR: {bm.colleague} knows {bm.name} ({bm.position}) at {self.company}{mover_flag}"
else:
if self.total_connections > 1:
return f"π {self.total_connections} connections at {self.company} (best: {bm.colleague} β {bm.name})"
return f"π {bm.colleague} knows {bm.name} ({bm.position}) at {self.company}{mover_flag}"
return f"π {self.total_connections} connection(s) at {self.company}"
@dataclass
class Mover:
"""Represents a contact who moved companies."""
name: str
colleague: str
company: str
position: str
is_new_position: bool
date_connected: str
@property
def alert_text(self) -> str:
position_change = " (new role!)" if self.is_new_position else ""
return f"π {self.name} (known by {self.colleague}) just moved to {self.company} as {self.position}{position_change}"
# =============================================================================
# COMPANY NAME NORMALIZATION
# =============================================================================
COMPANY_SUFFIXES = [
r'\s+plc\.?$', r'\s+ltd\.?$', r'\s+limited$', r'\s+inc\.?$',
r'\s+incorporated$', r'\s+corp\.?$', r'\s+corporation$',
r'\s+llc$', r'\s+llp$', r'\s+group$', r'\s+holdings$',
r'\s+uk$', r'\s+international$', r'\s+&\s+co\.?$',
r'\s+and\s+co\.?$', r'\s+partners$', r'\s+consulting$',
r'\s+services$', r'\s+solutions$', r'\(uk\)$', r'\(united kingdom\)$',
]
SENIOR_TITLES = [
# C-Suite
'ceo', 'chief executive', 'chief executive officer',
'cfo', 'chief financial', 'chief financial officer',
'coo', 'chief operating', 'chief operating officer',
'cto', 'chief technology', 'chief technology officer',
'cmo', 'chief marketing', 'chief marketing officer',
'cio', 'chief information', 'chief information officer',
'chro', 'chief human resources', 'chief people', 'chief people officer',
'cpo', 'chief product', 'cro', 'chief revenue',
'chief transformation', 'chief culture', 'chief digital',
# Director level
'director', 'managing director', 'md',
# VP / President
'vp', 'vice president', 'vice-president',
'president', 'chairman', 'chairwoman', 'chair',
# Partner / Head
'partner', 'head of', 'global head', 'regional head',
# General management
'general manager', 'gm',
# Programme / transformation leadership
'programme director', 'program director',
'head of transformation', 'transformation director',
'head of change', 'director of change',
'head of people', 'director of people',
'head of hr', 'director of hr',
'head of organisational', 'director of organisational',
'head of strategy', 'director of strategy',
'head of operations', 'director of operations',
'head of digital', 'director of digital',
'head of technology', 'director of technology',
'head of finance', 'director of finance',
'head of pmo', 'portfolio director',
# Senior individual contributors (but NOT "senior analyst", "senior assistant" etc.)
'principal consultant', 'principal advisor',
# Council-specific
'chief executive', 'deputy chief executive',
'director of resources', 'director of people',
's151 officer', 'monitoring officer',
]
# Titles that should NEVER be surfaced as the recommended contact β
# regardless of is_senior flag or recency. These are support/admin/
# junior roles that a partner should not be cold-approaching.
EXCLUDED_CONTACT_TITLES = [
'assistant', 'administrator', 'coordinator', 'receptionist',
'intern', 'apprentice', 'graduate', 'trainee', 'junior',
'analyst', # too broad on its own β "senior analyst" is fine but plain "analyst" is not
'support', # "HR Support", "IT Support"
'executive assistant', # EA is admin, not executive
'personal assistant', 'pa to',
'officer', # generic β "HR Officer", "Finance Officer" etc. (too junior)
'specialist', # often mid-level; "HR Specialist" is not a decision-maker
'advisor', # on its own too junior; "Senior Advisor" is fine
'associate', # consulting junior grade
]
def is_excluded_contact(position: str) -> bool:
"""True if this title should be filtered OUT of digest contact recommendations.
More conservative than is_senior β we'd rather show no contact than a junior one."""
if not position:
return False
pos = position.lower()
# Never exclude if a seniority qualifier is present
if any(q in pos for q in ('senior ', 'lead ', 'head ', 'chief ', 'director',
'vp ', 'principal ', 'managing ')):
return False
return any(excl in pos for excl in EXCLUDED_CONTACT_TITLES)
def normalize_company(company: str) -> str:
"""Normalize company name for matching."""
if not company:
return ""
name = company.lower().strip()
for suffix in COMPANY_SUFFIXES:
name = re.sub(suffix, '', name, flags=re.IGNORECASE)
name = re.sub(r'[^\w\s]', ' ', name)
name = ' '.join(name.split())
return name.strip()
def is_senior_position(position: str) -> bool:
"""Check if a position is C-Suite or Director level."""
if not position:
return False
pos_lower = position.lower()
for title in SENIOR_TITLES:
if title in pos_lower:
return True
return False
def match_role(target_role: str, actual_position: str) -> float:
"""Calculate how well a position matches a target role (0-100)."""
if not target_role or not actual_position:
return 0.0
target = target_role.lower().strip()
actual = actual_position.lower().strip()
if target == actual:
return 100.0
target_words = set(target.split()) - {'of', 'the', 'and', 'at', 'for', 'in', 'a', 'an'}
actual_words = set(actual.split()) - {'of', 'the', 'and', 'at', 'for', 'in', 'a', 'an'}
if target_words and actual_words:
overlap = len(target_words & actual_words)
max_words = max(len(target_words), len(actual_words))
word_score = (overlap / max_words) * 100 if max_words > 0 else 0
else:
word_score = 0
if FUZZY_AVAILABLE:
fuzzy_score = fuzz.token_sort_ratio(target, actual)
return max(word_score, fuzzy_score)
return word_score
# =============================================================================
# DATABASE OPERATIONS
# =============================================================================
def get_connection():
"""Create database connection."""
return sqlite3.connect(DATABASE)
def init_network_tables():
"""Initialize network database tables, handling schema migration."""
conn = get_connection()
cursor = conn.cursor()
# Check if old schema exists (from ingest_networks.py)
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='network_graph'")
table_exists = cursor.fetchone() is not None
if table_exists:
# Check columns to see which schema we have
cursor.execute("PRAGMA table_info(network_graph)")
columns = {row[1] for row in cursor.fetchall()}
# Old schema has 'connection_name', new schema has 'contact_name'
if 'connection_name' in columns and 'contact_name' not in columns:
# Migrate from old schema to new schema
print("Migrating network_graph from old schema...")
# Create new table
cursor.execute("""
CREATE TABLE IF NOT EXISTS network_graph_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
colleague_owner TEXT NOT NULL,
contact_name TEXT NOT NULL,
company TEXT,
company_normalized TEXT,
position TEXT,
date_connected TEXT,
is_senior INTEGER DEFAULT 0,
status TEXT DEFAULT 'ACTIVE',
is_new_company INTEGER DEFAULT 0,
is_new_position INTEGER DEFAULT 0,
source_file TEXT,
date_imported TEXT NOT NULL
)
""")
# Migrate data
cursor.execute("""
INSERT INTO network_graph_new (
colleague_owner, contact_name, company, company_normalized,
position, date_connected, is_senior, status,
is_new_company, is_new_position, source_file, date_imported
)
SELECT
COALESCE(source_colleague, 'Unknown'),
connection_name,
connection_company,
connection_company_normalized,
connection_title,
connected_on,
COALESCE(is_senior, 0),
'ACTIVE',
0,
0,
source_file,
COALESCE(date_imported, datetime('now'))
FROM network_graph
""")
# Swap tables
cursor.execute("DROP TABLE network_graph")
cursor.execute("ALTER TABLE network_graph_new RENAME TO network_graph")
print("Migration complete!")
# Add missing columns if needed (for partial migrations)
if 'status' not in columns:
try:
cursor.execute("ALTER TABLE network_graph ADD COLUMN status TEXT DEFAULT 'ACTIVE'")
except:
pass
if 'is_new_company' not in columns:
try:
cursor.execute("ALTER TABLE network_graph ADD COLUMN is_new_company INTEGER DEFAULT 0")
except:
pass
if 'is_new_position' not in columns:
try:
cursor.execute("ALTER TABLE network_graph ADD COLUMN is_new_position INTEGER DEFAULT 0")
except:
pass
else:
# Create fresh table with new schema
cursor.execute("""
CREATE TABLE IF NOT EXISTS network_graph (
id INTEGER PRIMARY KEY AUTOINCREMENT,
colleague_owner TEXT NOT NULL,
contact_name TEXT NOT NULL,
company TEXT,
company_normalized TEXT,
position TEXT,
date_connected TEXT,
is_senior INTEGER DEFAULT 0,
status TEXT DEFAULT 'ACTIVE',
is_new_company INTEGER DEFAULT 0,
is_new_position INTEGER DEFAULT 0,
source_file TEXT,
date_imported TEXT NOT NULL,
UNIQUE(contact_name, company, colleague_owner)
)
""")
# Create indexes (safe to run multiple times)
try:
cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_company_norm ON network_graph(company_normalized)")
except:
pass
try:
cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_colleague ON network_graph(colleague_owner)")
except:
pass
try:
cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_status ON network_graph(status)")
except:
pass
try:
cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_movers ON network_graph(is_new_company)")
except:
pass
# Team members table
cursor.execute("""
CREATE TABLE IF NOT EXISTS team_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
connections_count INTEGER DEFAULT 0,
movers_count INTEGER DEFAULT 0,
last_import TEXT
)
""")
conn.commit()
conn.close()
def get_preserved_owners() -> list:
"""Owners whose connections survive a clear-and-reload.
Some valuable networks are no longer in the team's master export β e.g.
a colleague who has left but whose relationships we still have access
to. Without this, a clear_existing reload (the app's upload path always
uses one) would silently delete them, and the data is unrecoverable
from the new sheet. Configured in config.yaml > network_preserve_owners.
"""
try:
import yaml
cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.yaml")
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = yaml.safe_load(f) or {}
return [str(o).strip() for o in (cfg.get("network_preserve_owners") or []) if str(o).strip()]
except Exception:
return []
def clear_network_data():
"""Clear network data, keeping any owners listed in
config.yaml > network_preserve_owners (see get_preserved_owners)."""
preserved = get_preserved_owners()
conn = get_connection()
cursor = conn.cursor()
if preserved:
placeholders = ",".join("?" * len(preserved))
cursor.execute(
f"DELETE FROM network_graph WHERE colleague_owner NOT IN ({placeholders})",
preserved,
)
cursor.execute(
f"DELETE FROM team_members WHERE name NOT IN ({placeholders})",
preserved,
)
else:
cursor.execute("DELETE FROM network_graph")
cursor.execute("DELETE FROM team_members")
conn.commit()
conn.close()
# =============================================================================
# CSV LOADING
# =============================================================================
# Column name variations we accept
COLUMN_MAPPINGS = {
'owner': ['Owner', 'owner', 'Colleague', 'Team Member', 'Connected To', 'Source'],
# NOTE: 'First Name' deliberately excluded β when only First/Last Name
# exist (no combined Full Name column), the loader combines them via the
# firstname/lastname branch. Including 'First Name' here would short-
# circuit that and store first-name-only as the contact name.
'full_name': ['Full Name', 'FullName', 'Name', 'Contact Name'],
'first_name': ['First Name', 'FirstName', 'first_name'],
'last_name': ['Last Name', 'LastName', 'last_name'],
'company': ['Company', 'company', 'Organization', 'Organisation', 'Employer'],
'position': ['Position', 'position', 'Title', 'Job Title', 'Role'],
# Order matters: flag-style columns first. The team's master sheet has
# both 'Position Change?' (Y/N flag) and 'New Position' (text β the new
# role title); we want the flag, never the text column.
'new_company': ['Company Change?', 'New Company?', 'NewCompany', 'Company Changed', 'Moved'],
'new_position': ['Position Change?', 'New Position?', 'NewPosition', 'Role Changed', 'Promoted'],
'date_connected': ['Date Connected', 'Connected On', 'Connection Date', 'Date'],
}
def find_column(headers: list, column_type: str) -> Optional[str]:
"""Find the actual column name from headers."""
possible_names = COLUMN_MAPPINGS.get(column_type, [])
for name in possible_names:
if name in headers:
return name
return None
def is_yes(value: str) -> bool:
"""Check if a value represents 'Yes'."""
if not value:
return False
return value.strip().upper() in ['Y', 'YES', 'TRUE', '1', 'X']
def load_csv(filepath: str = DEFAULT_CSV_FILE, clear_existing: bool = False) -> dict:
"""
Load the LinkedIn Connection Data from CSV or XLSX.
Args:
filepath: Path to the CSV or XLSX file
clear_existing: If True, clear existing data before loading
Returns:
Dict with import statistics
"""
if not os.path.exists(filepath):
return {
'success': False,
'error': f'File not found: {filepath}',
'imported': 0
}
# Convert XLSX to CSV if needed
if filepath.lower().endswith('.xlsx'):
try:
filepath = convert_xlsx_to_csv(filepath)
except Exception as e:
return {
'success': False,
'error': f'XLSX conversion failed: {e}',
'imported': 0
}
init_network_tables()
if clear_existing:
clear_network_data()
stats = {
'success': True,
'file': filepath,
'total_rows': 0,
'imported': 0,
'skipped': 0,
'errors': 0,
'movers': 0,
'promoted': 0,
'colleagues': set(),
}
conn = get_connection()
cursor = conn.cursor()
try:
for encoding in ['utf-8', 'utf-8-sig', 'latin-1', 'cp1252']:
try:
with open(filepath, 'r', encoding=encoding) as f:
content = f.read()
lines = content.split('\n')
# Find header row
header_idx = 0
for i, line in enumerate(lines[:10]):
if any(col in line for col in ['Owner', 'Full Name', 'Company', 'Position']):
header_idx = i
break
f.seek(0)
for _ in range(header_idx):
f.readline()
reader = csv.DictReader(f)
headers = reader.fieldnames or []
# Find column mappings
owner_col = find_column(headers, 'owner')
fullname_col = find_column(headers, 'full_name')
firstname_col = find_column(headers, 'first_name')
lastname_col = find_column(headers, 'last_name')
company_col = find_column(headers, 'company')
position_col = find_column(headers, 'position')
new_company_col = find_column(headers, 'new_company')
new_position_col = find_column(headers, 'new_position')
date_col = find_column(headers, 'date_connected')
stats['detected_columns'] = {
'owner': owner_col,
'full_name': fullname_col,
'first_name': firstname_col,
'last_name': lastname_col,
'company': company_col,
'position': position_col,
'new_company_flag': new_company_col,
'new_position_flag': new_position_col,
'date_connected': date_col,
}
stats['headers'] = list(headers)
for row in reader:
stats['total_rows'] += 1
try:
# Extract owner
owner = row.get(owner_col, '').strip() if owner_col else 'Unknown'
# Extract name
if fullname_col:
contact_name = row.get(fullname_col, '').strip()
else:
first = row.get(firstname_col, '').strip() if firstname_col else ''
last = row.get(lastname_col, '').strip() if lastname_col else ''
contact_name = f"{first} {last}".strip()
company = row.get(company_col, '').strip() if company_col else ''
position = row.get(position_col, '').strip() if position_col else ''
date_connected = row.get(date_col, '').strip() if date_col else ''
# Movement tracking
is_new_company = is_yes(row.get(new_company_col, '')) if new_company_col else False
is_new_position = is_yes(row.get(new_position_col, '')) if new_position_col else False
# Skip if no name
if not contact_name:
stats['skipped'] += 1
continue
# Determine status
if is_new_company:
status = 'MOVER'
stats['movers'] += 1
elif is_new_position:
status = 'PROMOTED'
stats['promoted'] += 1
else:
status = 'ACTIVE'
company_normalized = normalize_company(company)
is_senior = 1 if is_senior_position(position) else 0
stats['colleagues'].add(owner)
cursor.execute("""
INSERT OR REPLACE INTO network_graph (
colleague_owner, contact_name, company, company_normalized,
position, date_connected, is_senior, status,
is_new_company, is_new_position, source_file, date_imported
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
owner, contact_name, company, company_normalized,
position, date_connected, is_senior, status,
1 if is_new_company else 0,
1 if is_new_position else 0,
filepath, datetime.now().isoformat()
))
stats['imported'] += 1
except Exception as e:
stats['errors'] += 1
break
except UnicodeDecodeError:
continue
conn.commit()
# Update team members
for colleague in stats['colleagues']:
cursor.execute("SELECT COUNT(*) FROM network_graph WHERE colleague_owner = ?", (colleague,))
count = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM network_graph WHERE colleague_owner = ? AND is_new_company = 1", (colleague,))
movers = cursor.fetchone()[0]
cursor.execute("""
INSERT OR REPLACE INTO team_members (name, connections_count, movers_count, last_import)
VALUES (?, ?, ?, ?)
""", (colleague, count, movers, datetime.now().isoformat()))
conn.commit()
stats['colleagues'] = list(stats['colleagues'])
except Exception as e:
stats['success'] = False
stats['error'] = str(e)
finally:
conn.close()
return stats
# Alias for backwards compatibility
load_master_csv = load_csv
# =============================================================================
# MATCHING ENGINE
# =============================================================================
def find_network_hit(
company: str,
target_role: str = None,
min_company_score: int = 75,
min_role_score: int = 60
) -> NetworkHit:
"""Find network connections at a company with tiered matching."""
if not company:
return NetworkHit(
company=company, target_role=target_role, matches=[],
best_match=None, tier=ConnectionTier.NO_CONNECTION, total_connections=0
)
conn = get_connection()
cursor = conn.cursor()
target_normalized = normalize_company(company)
cursor.execute("""
SELECT contact_name, company, company_normalized, position,
colleague_owner, is_senior, is_new_company
FROM network_graph
""")
rows = cursor.fetchall()
conn.close()
matches = []
for row in rows:
name, orig_company, norm_company, position, colleague, is_senior, is_mover = row
if FUZZY_AVAILABLE:
company_score = max(
fuzz.ratio(target_normalized, norm_company or ''),
fuzz.partial_ratio(target_normalized, norm_company or ''),
fuzz.token_sort_ratio(target_normalized, norm_company or '')
)
else:
company_score = 100 if target_normalized in (norm_company or '') or (norm_company or '') in target_normalized else 0
if company_score < min_company_score:
continue
role_score = match_role(target_role, position) if target_role else 0.0
if target_role and role_score >= min_role_score:
tier = ConnectionTier.TIER_1_EXACT_ROLE
elif is_senior:
tier = ConnectionTier.TIER_2_SENIOR
else:
tier = ConnectionTier.TIER_3_COMPANY
match = ConnectionMatch(
name=name, company=orig_company or '', position=position or "Unknown",
colleague=colleague, tier=tier, match_score=company_score,
is_senior=bool(is_senior), is_mover=bool(is_mover), role_match_score=role_score
)
matches.append(match)
matches.sort(key=lambda m: (m.tier.value, -m.match_score, -m.role_match_score))
if not matches:
return NetworkHit(
company=company, target_role=target_role, matches=[],
best_match=None, tier=ConnectionTier.NO_CONNECTION, total_connections=0
)
return NetworkHit(
company=company, target_role=target_role, matches=matches,
best_match=matches[0], tier=matches[0].tier, total_connections=len(matches)
)
# =============================================================================
# SERVICE-AFFINITY ROUTING
# =============================================================================
# Team member specialisations (loaded from config at runtime, with fallback)
_TEAM_SERVICE_FOCUS = None
def _get_team_service_focus() -> dict:
"""Load team member service focus from config.yaml (cached)."""
global _TEAM_SERVICE_FOCUS
if _TEAM_SERVICE_FOCUS is not None:
return _TEAM_SERVICE_FOCUS
try:
import yaml
with open('config.yaml', 'r') as f:
config = yaml.safe_load(f)
team = config.get('team', [])
_TEAM_SERVICE_FOCUS = {
m['name'].lower(): m.get('service_focus', [])
for m in team
}
except Exception:
_TEAM_SERVICE_FOCUS = {
'piers lyon': ['transformation_delivery', 'culture_capability'],
'adam': ['transformation_delivery'],
'stuart': ['culture_capability'],
}
return _TEAM_SERVICE_FOCUS
def find_network_hit_with_affinity(
company: str,
target_role: str = None,
dominant_service: str = None,
td_score: int = 0,
cc_score: int = 0,
min_company_score: int = 75,
min_role_score: int = 60,
) -> 'NetworkHit':
"""Enhanced network routing that considers colleague service specialisation.
When multiple colleagues have connections at the same company, prefer
the colleague whose service_focus matches the company's dominant need.
Args:
company: Target company name
target_role: Optional target role/position
dominant_service: 'transformation_delivery' or 'culture_capability' (explicit)
td_score: Company's TD score (used to infer dominant service if not explicit)
cc_score: Company's CC score (used to infer dominant service if not explicit)
"""
# Get base matches
hit = find_network_hit(company, target_role, min_company_score, min_role_score)
if not hit.has_connection or len(hit.matches) <= 1:
return hit # No routing decision needed
# Determine dominant service need
if not dominant_service:
if td_score > cc_score + 10:
dominant_service = 'transformation_delivery'
elif cc_score > td_score + 10:
dominant_service = 'culture_capability'
else:
return hit # Scores are close, no strong affinity preference
team_focus = _get_team_service_focus()
# Re-sort matches: prefer colleagues whose service_focus includes the dominant service
def affinity_sort_key(m: ConnectionMatch):
colleague_lower = (m.colleague or '').lower()
focus = team_focus.get(colleague_lower, [])
has_affinity = 1 if dominant_service in focus else 0
# Primary: tier (lower = better), Secondary: affinity (1 = better), Tertiary: match_score
return (m.tier.value, -has_affinity, -m.match_score, -m.role_match_score)
sorted_matches = sorted(hit.matches, key=affinity_sort_key)
return NetworkHit(
company=company,
target_role=target_role,
matches=sorted_matches,
best_match=sorted_matches[0],
tier=sorted_matches[0].tier,
total_connections=len(sorted_matches),
)
# =============================================================================
# MOVERS ALERT
# =============================================================================
def get_movers(limit: int = 50) -> list[Mover]:
"""Get contacts who recently moved companies."""
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT contact_name, colleague_owner, company, position,
is_new_position, date_connected
FROM network_graph
WHERE is_new_company = 1
ORDER BY date_imported DESC
LIMIT ?
""", (limit,))
rows = cursor.fetchall()
conn.close()
movers = []
for row in rows:
movers.append(Mover(
name=row[0], colleague=row[1], company=row[2] or 'Unknown',
position=row[3] or 'Unknown', is_new_position=bool(row[4]),
date_connected=row[5] or ''
))
return movers
def get_movers_by_colleague(colleague: str = None) -> dict:
"""Get movers grouped by colleague."""
conn = get_connection()
cursor = conn.cursor()
if colleague:
cursor.execute("""
SELECT contact_name, colleague_owner, company, position,
is_new_position, date_connected
FROM network_graph
WHERE is_new_company = 1 AND colleague_owner = ?
ORDER BY date_imported DESC
""", (colleague,))
else:
cursor.execute("""
SELECT contact_name, colleague_owner, company, position,
is_new_position, date_connected
FROM network_graph
WHERE is_new_company = 1
ORDER BY colleague_owner, date_imported DESC
""")
rows = cursor.fetchall()
conn.close()
by_colleague = {}
for row in rows:
mover = Mover(
name=row[0], colleague=row[1], company=row[2] or 'Unknown',
position=row[3] or 'Unknown', is_new_position=bool(row[4]),
date_connected=row[5] or ''
)
if mover.colleague not in by_colleague:
by_colleague[mover.colleague] = []
by_colleague[mover.colleague].append(mover)
return by_colleague
def generate_movers_report() -> str:
"""Generate a formatted movers alert report."""
movers = get_movers()
if not movers:
return "No movers detected in your network."
lines = []
lines.append("=" * 60)
lines.append("π MOVERS ALERT - Network Movement Report")
lines.append(f" Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
lines.append("=" * 60)
lines.append(f"\n {len(movers)} contacts have moved to new companies!\n")
lines.append("-" * 60)
# Group by colleague
by_colleague = {}
for m in movers:
if m.colleague not in by_colleague:
by_colleague[m.colleague] = []
by_colleague[m.colleague].append(m)
for colleague, colleague_movers in by_colleague.items():
lines.append(f"\nπ€ {colleague}'s Network ({len(colleague_movers)} movers):")
lines.append("-" * 40)
for m in colleague_movers:
new_role = " π NEW ROLE" if m.is_new_position else ""
lines.append(f" π {m.name}")
lines.append(f" β Now at: {m.company}")
lines.append(f" β Role: {m.position}{new_role}")
lines.append(f" π‘ ACTION: Reach out to congratulate and reconnect!")
lines.append("")
lines.append("=" * 60)
lines.append("End of Movers Report")
return "\n".join(lines)
# =============================================================================
# STATISTICS
# =============================================================================
def get_network_stats() -> dict:
"""Get network statistics."""
conn = get_connection()
cursor = conn.cursor()
stats = {}
cursor.execute("SELECT COUNT(*) FROM network_graph")
stats['total_connections'] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(DISTINCT company_normalized) FROM network_graph WHERE company_normalized != ''")
stats['unique_companies'] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM network_graph WHERE is_senior = 1")
stats['senior_connections'] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM network_graph WHERE is_new_company = 1")
stats['movers'] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM network_graph WHERE is_new_position = 1")
stats['promoted'] = cursor.fetchone()[0]
cursor.execute("""
SELECT colleague_owner, COUNT(*) as count
FROM network_graph
GROUP BY colleague_owner
ORDER BY count DESC
""")
stats['by_colleague'] = cursor.fetchall()
cursor.execute("SELECT name, connections_count, movers_count, last_import FROM team_members ORDER BY connections_count DESC")
stats['team_members'] = cursor.fetchall()
conn.close()
return stats
# =============================================================================
# BRIEFING INTEGRATION
# =============================================================================
def format_network_hit_for_briefing(hit: NetworkHit) -> str:
"""Format a NetworkHit for the daily briefing."""
if not hit.has_connection:
return ""
lines = []
bm = hit.best_match
if hit.tier == ConnectionTier.TIER_1_EXACT_ROLE:
mover_flag = " π RECENTLY MOVED!" if bm.is_mover else ""
lines.append(f" π― NETWORK HIT: {bm.colleague} knows {bm.name} ({bm.position}) at {hit.company}!{mover_flag}")
elif hit.tier == ConnectionTier.TIER_2_SENIOR:
mover_flag = " π" if bm.is_mover else ""
lines.append(f" β SENIOR CONNECTION: {bm.colleague} knows {bm.name} ({bm.position}){mover_flag}")
else:
if hit.total_connections > 1:
by_colleague = {}
for m in hit.matches:
if m.colleague not in by_colleague:
by_colleague[m.colleague] = []
by_colleague[m.colleague].append(m)
for colleague, conns in list(by_colleague.items())[:2]:
if len(conns) > 1:
lines.append(f" π {colleague} knows {len(conns)} people at {hit.company}")
else:
lines.append(f" π {colleague} knows {conns[0].name} ({conns[0].position})")
else:
mover_flag = " π" if bm.is_mover else ""
lines.append(f" π {bm.colleague} knows {bm.name} ({bm.position}){mover_flag}")
return "\n".join(lines)
def check_lead_connections(company: str, role: str = None) -> dict:
"""Check network connections for a lead."""
hit = find_network_hit(company, role)
return {
'has_connection': hit.has_connection,
'tier': hit.tier.value,
'tier_name': hit.best_match.tier_label if hit.best_match else 'NO CONNECTION',
'tier_emoji': hit.best_match.tier_emoji if hit.best_match else 'βοΈ',
'summary': hit.summary,
'total_connections': hit.total_connections,
'best_match': {
'name': hit.best_match.name,
'position': hit.best_match.position,
'colleague': hit.best_match.colleague,
'is_senior': hit.best_match.is_senior,
'is_mover': hit.best_match.is_mover,
} if hit.best_match else None,
'all_matches': [
{
'name': m.name, 'position': m.position, 'colleague': m.colleague,
'tier': m.tier_label, 'is_senior': m.is_senior, 'is_mover': m.is_mover,
}
for m in hit.matches[:10]
],
'briefing_text': format_network_hit_for_briefing(hit),
}
# =============================================================================
# CLI INTERFACE
# =============================================================================
def print_stats():
"""Print network statistics."""
stats = get_network_stats()
print(f"\n{'='*60}")
print("π NETWORK INTELLIGENCE STATS")
print(f"{'='*60}")
print(f"\n Total Connections: {stats['total_connections']}")
print(f" Unique Companies: {stats['unique_companies']}")
print(f" Senior Connections: {stats['senior_connections']}")
print(f" π Movers: {stats['movers']}")
print(f" π Promoted: {stats['promoted']}")
if stats['by_colleague']:
print(f"\n Connections by Team Member:")
for colleague, count in stats['by_colleague']:
print(f" β’ {colleague}: {count}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Network Loader - LinkedIn Connection Intelligence')
parser.add_argument('--file', type=str, default=DEFAULT_CSV_FILE, help='CSV file to load')
parser.add_argument('--clear', action='store_true', help='Clear existing data before loading')
parser.add_argument('--match', type=str, help='Test matching against a company')
parser.add_argument('--role', type=str, help='Target role to match (used with --match)')
parser.add_argument('--movers', action='store_true', help='Show movers alert report')
parser.add_argument('--stats', action='store_true', help='Show network statistics')
args = parser.parse_args()
init_network_tables()
if args.stats:
print_stats()
elif args.movers:
print(generate_movers_report())
elif args.match:
print(f"\nπ Finding connections at: {args.match}")
if args.role:
print(f" Target role: {args.role}")
hit = find_network_hit(args.match, args.role)
print(f"\n{hit.summary}")
if hit.matches:
print(f"\n All Connections ({hit.total_connections}):")
for m in hit.matches[:10]:
senior_flag = " β" if m.is_senior else ""
mover_flag = " π" if m.is_mover else ""
print(f" {m.tier_emoji} {m.name} ({m.position}){senior_flag}{mover_flag}")
print(f" Via: {m.colleague} | Match: {m.match_score:.0f}%")
if hit.has_connection:
print(f"\nπ Briefing Format:")
print(format_network_hit_for_briefing(hit))
else:
print(f"\nπ₯ Loading: {args.file}")
result = load_csv(args.file, clear_existing=args.clear)
if result['success']:
print(f"\nβ
Import Complete!")
print(f" Rows processed: {result['total_rows']}")
print(f" Imported: {result['imported']}")
print(f" Skipped: {result['skipped']}")
print(f" π Movers: {result['movers']}")
print(f" π Promoted: {result['promoted']}")
print(f" Team Members: {', '.join(result.get('colleagues', []))}")
print_stats()
else:
print(f"\nβ Import Failed: {result.get('error', 'Unknown')}")
"""
Network Loader Module (network_loader.py)
Loads LinkedIn Connection Data CSV with movement tracking.
Expected CSV Columns:
- Owner: Colleague who owns the connection (e.g., 'Adam', 'Adela')
- Full Name: Contact's full name
- Company: Current company
- Position: Current position/title
- New Company?: 'Y' or 'N' - indicates if contact moved companies
- New Position?: 'Y' or 'N' - indicates if contact changed roles
- Date Connected: When the connection was made (optional)
Usage:
python network_loader.py # Load CSV
python network_loader.py --file custom.csv # Load custom file
python network_loader.py --match "Premier Foods" # Find connections
python network_loader.py --movers # Show movers alert
python network_loader.py --stats # Network statistics
"""
import os
import csv
import sqlite3
import re
from datetime import datetime
from typing import Optional
from dataclasses import dataclass
from enum import Enum
# Try to import fuzzy matching
try:
from rapidfuzz import fuzz, process
FUZZY_AVAILABLE = True
except ImportError:
FUZZY_AVAILABLE = False
print("Warning: rapidfuzz not installed. Install with: pip install rapidfuzz")
DATABASE = "leads.db"
DEFAULT_CSV_FILE = "data/my_team_connections.csv"
def convert_xlsx_to_csv(xlsx_path: str) -> str:
"""Convert an XLSX file to CSV format, returning the CSV path.
The team's master workbook contains many sheets (pivot tables, dropdowns,
message templates, etc.). `wb.active` returns whichever sheet was active
when the file was last saved β often *not* the data sheet. Instead, scan
every sheet, find those whose first ~15 rows contain the connection-data
header signature (Company + Position, plus either Owner/Full Name or
First Name + Last Name), and pick the largest match. Falls back to
`wb.active` if nothing looks like data.
"""
import openpyxl
csv_path = xlsx_path.rsplit('.', 1)[0] + '.csv'
wb = openpyxl.load_workbook(xlsx_path, read_only=True, data_only=True)
REQUIRED_TOKENS = {"company", "position"}
NAME_TOKENS = {"full name", "first name", "last name", "owner", "name"}
MOVEMENT_TOKENS = {"position change?", "company change?", "new position?", "new company?"}
def _sheet_score(ws) -> tuple[int, int, int] | None:
"""Return (priority, header_row_idx, n_rows) if sheet looks like
connection data; None otherwise. Higher priority = preferred.
Priority tiers (most preferred last):
0 β connection data, no Owner
1 β connection data with Owner
2 β connection data with Owner AND movement tracking
(Position Change? / Company Change?). The team's "New Data"
sheet has these and drives MOVERS/PROMOTED signals.
"""
try:
for header_idx, row in enumerate(ws.iter_rows(values_only=True, max_row=15)):
cells = {str(c).strip().lower() for c in row if c is not None}
if REQUIRED_TOKENS.issubset(cells) and (cells & NAME_TOKENS):
has_owner = "owner" in cells
has_movement = bool(cells & MOVEMENT_TOKENS)
if has_owner and has_movement:
priority = 2
elif has_owner:
priority = 1
else:
priority = 0
return (priority, header_idx, ws.max_row or 0)
except Exception:
return None
return None
best = None # (priority, n_rows, header_idx, sheet_name)
for sn in wb.sheetnames:
ws = wb[sn]
info = _sheet_score(ws)
if info is None:
continue
priority, header_idx, n_rows = info
candidate = (priority, n_rows, header_idx, sn)
if best is None or candidate > best:
best = candidate