-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
261 lines (216 loc) · 8.19 KB
/
main.py
File metadata and controls
261 lines (216 loc) · 8.19 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
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
"""
Algorzen Pulse - Main Orchestration Script
Author: Rishi Singh | Algorzen Research Division © 2025
Command-line interface for real-time trend monitoring and report generation.
Coordinates data streaming, analysis, AI summarization, and reporting.
"""
import argparse
import sys
from pathlib import Path
from datetime import datetime
from data_stream import DataStream
from trend_analyzer import TrendAnalyzer
from ai_summary import AISummaryEngine
from report_generator import ReportGenerator
def print_banner():
"""Display Algorzen Pulse branding banner."""
banner = """
╔══════════════════════════════════════════════════════════════╗
║ ║
║ ALGORZEN PULSE ║
║ Real-Time Trend & Data Monitoring ║
║ ║
║ "The heartbeat of your data." ║
║ ║
║ Algorzen Research Division © 2025 — Author: Rishi Singh ║
║ ║
╚══════════════════════════════════════════════════════════════╝
"""
print(banner)
def generate_sample_data(output_path: str, num_days: int = 30):
"""
Generate sample live feed data.
Args:
output_path: Where to save the generated data
num_days: Number of days of historical data
"""
print("\n🔧 Generating sample data...")
stream = DataStream()
df = stream.generate_live_feed(
output_path=output_path,
num_days=num_days,
metrics=['sales', 'engagement', 'conversions', 'revenue']
)
print(f"\n✅ Sample data generated successfully!")
print(f" Location: {output_path}")
print(f" Records: {len(df):,}")
print(f" Date Range: {df['timestamp'].min()} to {df['timestamp'].max()}")
def run_analysis(
input_path: str,
use_openai: bool = False,
window_short: int = 24,
window_long: int = 168
):
"""
Run complete trend analysis and report generation.
Args:
input_path: Path to input CSV data
use_openai: Whether to use OpenAI for summary generation
window_short: Short-term moving average window
window_long: Long-term moving average window
"""
print("\n🚀 Starting Algorzen Pulse analysis pipeline...\n")
# Step 1: Load data
print("📥 Step 1/5: Loading data stream...")
stream = DataStream()
if not Path(input_path).exists():
print(f"❌ Error: Input file not found: {input_path}")
print("💡 Tip: Run with --generate-sample to create sample data first")
sys.exit(1)
df = stream.load_stream(input_path)
# Step 2: Analyze trends
print("\n📊 Step 2/5: Analyzing trends...")
analyzer = TrendAnalyzer(df)
trends = analyzer.analyze_all_metrics(
window_short=window_short,
window_long=window_long
)
# Get insights and summary stats
insights = analyzer.get_top_insights(limit=5)
summary_stats = analyzer.get_summary_stats()
print(f"\n 📈 Trend Summary:")
print(f" - Metrics Increasing: {summary_stats['metrics_increasing']} ↑")
print(f" - Metrics Declining: {summary_stats['metrics_declining']} ↓")
print(f" - Metrics Stable: {summary_stats['metrics_stable']} ⚖️")
print(f" - High Priority Insights: {summary_stats['high_priority_insights']}")
# Step 3: Generate AI summary
print(f"\n🤖 Step 3/5: Generating executive summary...")
print(f" Mode: {'OpenAI GPT-4' if use_openai else 'Rule-based fallback'}")
ai_engine = AISummaryEngine(use_openai=use_openai)
executive_summary = ai_engine.generate_executive_summary(
trends, insights, summary_stats
)
# Step 4: Generate reports
print(f"\n📄 Step 4/5: Creating comprehensive reports...")
report_gen = ReportGenerator(output_dir="reports")
report_files = report_gen.generate_report(
df=df,
trends=trends,
insights=insights,
summary_stats=summary_stats,
executive_summary=executive_summary,
use_openai=use_openai
)
# Step 5: Display results
print(f"\n✨ Step 5/5: Analysis complete!\n")
print("="*60)
print("RESULTS")
print("="*60)
print(f"\n📊 Report ID: {report_files['report_id']}")
print(f"\n📁 Generated Files:")
print(f" • PDF Report: {report_files['pdf']}")
print(f" • HTML Report: {report_files['html']}")
print(f" • Metadata: {report_files['metadata']}")
print(f"\n🎯 Top 3 Insights:")
for idx, insight in enumerate(insights[:3], 1):
priority_icon = {
'high': '🔴',
'medium': '🟡',
'low': '🟢'
}.get(insight['priority'], '⚪')
print(f" {priority_icon} [{insight['priority'].upper()}] {insight['message']}")
print("\n" + "="*60)
print("✅ ALGORZEN PULSE ANALYSIS COMPLETE")
print("="*60)
print("\nAlgorzen Research Division © 2025 — Author: Rishi Singh\n")
def main():
"""Main entry point with CLI argument parsing."""
parser = argparse.ArgumentParser(
description='Algorzen Pulse - Real-Time Trend & Data Monitoring Engine',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Generate sample data
python main.py --generate-sample
# Run analysis with existing data
python main.py --input data/sample_live_feed.csv
# Run analysis with OpenAI integration
python main.py --input data/sample_live_feed.csv --use-openai
# Custom analysis windows
python main.py --input data/my_data.csv --window-short 12 --window-long 72
Author: Rishi Singh | Algorzen Research Division © 2025
"""
)
# Main arguments
parser.add_argument(
'--input',
type=str,
default='data/sample_live_feed.csv',
help='Path to input CSV data file (default: data/sample_live_feed.csv)'
)
parser.add_argument(
'--use-openai',
action='store_true',
help='Use OpenAI GPT-4 for executive summary generation'
)
parser.add_argument(
'--window-short',
type=int,
default=24,
help='Short-term moving average window in hours (default: 24)'
)
parser.add_argument(
'--window-long',
type=int,
default=168,
help='Long-term moving average window in hours (default: 168 = 1 week)'
)
# Data generation
parser.add_argument(
'--generate-sample',
action='store_true',
help='Generate sample data and exit'
)
parser.add_argument(
'--num-days',
type=int,
default=30,
help='Number of days of sample data to generate (default: 30)'
)
parser.add_argument(
'--output',
type=str,
default='data/sample_live_feed.csv',
help='Output path for generated sample data (default: data/sample_live_feed.csv)'
)
# Version
parser.add_argument(
'--version',
action='version',
version='Algorzen Pulse v1.0.0 - Author: Rishi Singh'
)
args = parser.parse_args()
# Display banner
print_banner()
# Handle generate sample mode
if args.generate_sample:
generate_sample_data(args.output, args.num_days)
return
# Run main analysis
run_analysis(
input_path=args.input,
use_openai=args.use_openai,
window_short=args.window_short,
window_long=args.window_long
)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n⚠️ Analysis interrupted by user")
sys.exit(0)
except Exception as e:
print(f"\n❌ Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)