-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_from_scratch.py
More file actions
198 lines (158 loc) Β· 6.37 KB
/
Copy pathsetup_from_scratch.py
File metadata and controls
198 lines (158 loc) Β· 6.37 KB
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
#!/usr/bin/env python3
"""
Complete setup script for FEC Contributions Database from scratch.
This script will:
1. Create all necessary tables
2. Process all contribution data
3. Load committee information
4. Build lookup tables for fast searching
5. Create indexes for performance
Usage: python3 setup_from_scratch.py [--public]
"""
import os
import sys
import sqlite3
import subprocess
import time
import argparse
from pathlib import Path
DB_PATH = "fec_contributions.db"
def run_script(script_name, description, *args):
"""Run a Python script and handle errors"""
print(f"\nπ {description}")
print(f" Running: python3 {script_name} {' '.join(args)}")
start_time = time.time()
try:
result = subprocess.run([sys.executable, script_name] + list(args),
check=True, capture_output=True, text=True)
elapsed = time.time() - start_time
print(f"β
{description} completed in {elapsed:.1f} seconds")
if result.stdout:
print(f" Output: {result.stdout.strip()}")
return True
except subprocess.CalledProcessError as e:
elapsed = time.time() - start_time
print(f"β {description} failed after {elapsed:.1f} seconds")
print(f" Error: {e.stderr.strip() if e.stderr else str(e)}")
return False
except FileNotFoundError:
print(f"β Script {script_name} not found")
return False
def create_base_tables():
"""Create the base database tables"""
print("\nπ Creating base database tables...")
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Create contributions table
print(" Creating contributions table...")
with open("table.sql", 'r') as f:
cursor.executescript(f.read())
# Create processed_files table for tracking
print(" Creating processed files tracking table...")
cursor.execute("""
CREATE TABLE IF NOT EXISTS processed_files (
filename TEXT PRIMARY KEY,
processed_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
print("β
Base tables created")
def create_lookup_tables():
"""Create all lookup and performance tables"""
print("\nπ Creating lookup and performance tables...")
# Create percentile tables
print(" Creating percentile tables...")
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
with open("percentile_tables.sql", 'r') as f:
cursor.executescript(f.read())
conn.commit()
conn.close()
# Create recipient lookup tables
print(" Creating recipient lookup tables...")
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
with open("recipient_lookup_table.sql", 'r') as f:
cursor.executescript(f.read())
conn.commit()
conn.close()
print("β
Lookup tables created")
def create_indexes():
"""Create database indexes for performance"""
print("\nπ Creating database indexes...")
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
with open("indexes.sql", 'r') as f:
cursor.executescript(f.read())
conn.commit()
conn.close()
print("β
Indexes created")
def main():
"""Main setup process"""
parser = argparse.ArgumentParser(description='Set up FEC database from scratch')
parser.add_argument('--skip-data', action='store_true', help='Skip data processing (tables only)')
args = parser.parse_args()
print("π― FEC Contributions Database - Complete Setup")
print("=" * 50)
# Check for required files
required_files = [
"table.sql", "percentile_tables.sql", "recipient_lookup_table.sql",
"indexes.sql", "process.py", "committee.py",
"build_percentile_tables.py", "build_recipient_lookup.py"
]
missing_files = [f for f in required_files if not Path(f).exists()]
if missing_files:
print(f"β Missing required files: {', '.join(missing_files)}")
return 1
# Check for data directory
if not args.skip_data and not Path("fec_data").exists():
print("β Data directory 'fec_data' not found")
print(" Please download and extract FEC data to the 'fec_data' directory")
return 1
# Remove existing database
if Path(DB_PATH).exists():
print(f"ποΈ Removing existing database: {DB_PATH}")
os.remove(DB_PATH)
# Step 1: Create base tables
create_base_tables()
if not args.skip_data:
# Step 2: Process contribution data
if not run_script("process.py", "Processing contribution data"):
print("β Failed to process contribution data")
return 1
# Step 3: Load committee information
if not run_script("committee.py", "Loading committee information"):
print("β Failed to load committee data")
return 1
# Step 4: Create lookup tables
create_lookup_tables()
# Step 5: Create indexes
create_indexes()
if not args.skip_data:
# Step 6: Build percentile tables
if not run_script("build_percentile_tables.py", "Building percentile lookup tables"):
print("β οΈ Percentile tables failed - you can build them later")
# Step 7: Build recipient lookup
if not run_script("build_recipient_lookup.py", "Building recipient lookup tables"):
print("β οΈ Recipient lookup failed - you can build it later")
print("\nπ Setup complete!")
print(f" Database: {DB_PATH}")
if not args.skip_data:
# Show database stats
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM contributions")
contrib_count = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM committees")
committee_count = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM recipient_lookup")
recipient_lookup_count = cursor.fetchone()[0]
print(f" π {contrib_count:,} contributions loaded")
print(f" ποΈ {committee_count:,} committees loaded")
print(f" π {recipient_lookup_count:,} recipients in lookup table")
conn.close()
print("\nπ You can now run the web app with: python3 app.py")
return 0
if __name__ == "__main__":
sys.exit(main())