-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlauncher.py
More file actions
1051 lines (857 loc) Β· 36.3 KB
/
Copy pathlauncher.py
File metadata and controls
1051 lines (857 loc) Β· 36.3 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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Social Media Surveillance System - Main Launcher
Entry point for the surveillance system with full Phase 5 UI integration.
"""
import sys
import time
import logging
import argparse
from pathlib import Path
from typing import List
# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('data/logs/surveillance_system.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
def attempt_auto_pyqt_fix():
"""Attempt to automatically fix PyQt6 issues"""
try:
import subprocess
import sys
import os
print("π§ Attempting automatic system fixes...")
# Fix 1: Update ChromeDriver
print(" π Updating ChromeDriver...")
try:
subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", "undetected-chromedriver"],
capture_output=True, check=False)
print(" β
ChromeDriver updated")
except:
pass
# Fix 2: Try to uninstall and reinstall PyQt6
print(" π Fixing PyQt6...")
try:
subprocess.run([sys.executable, "-m", "pip", "uninstall", "PyQt6", "-y"],
capture_output=True, check=False)
print(" β
PyQt6 uninstalled")
except:
pass
# Install PyQt6
result = subprocess.run([sys.executable, "-m", "pip", "install", "PyQt6"],
capture_output=True, text=True)
if result.returncode == 0:
print(" β
PyQt6 reinstalled successfully")
# Test if it works now
try:
from PyQt6.QtCore import QCoreApplication
print(" β
PyQt6 import test successful")
return True
except ImportError:
print(" β PyQt6 still not working, trying alternative fixes...")
# Try installing Visual C++ Redistributable dependencies
try:
subprocess.run([sys.executable, "-m", "pip", "install", "pyqt6-tools"],
capture_output=True, check=False)
print(" β
PyQt6 tools installed")
except:
pass
# Try PyQt5 as fallback
result = subprocess.run([sys.executable, "-m", "pip", "install", "PyQt5"],
capture_output=True, text=True)
if result.returncode == 0:
print(" β
PyQt5 installed as fallback")
return False # Don't retry with PyQt6, use CLI
print(" β Automatic fix failed")
return False
except Exception as e:
print(f" β Auto-fix error: {e}")
return False
def launch_ui_dashboard():
"""Launch the PyQt6 dashboard interface"""
try:
# Import PyQt6 components
from PyQt6.QtWidgets import QApplication
from PyQt6.QtCore import QSettings
# Import UI components
from ui.main_dashboard import MainDashboard
from ui.themes import load_saved_theme, get_theme_manager
from ui.realtime_updates import get_update_manager
print("π Launching Social Media Surveillance System - Phase 5 Dashboard")
print("=" * 70)
# Create QApplication
app = QApplication(sys.argv)
app.setApplicationName("Social Media Surveillance System")
app.setApplicationVersion("1.0.0 - Phase 5")
app.setOrganizationName("SMSS Team")
# Load and apply saved theme
print("π¨ Loading UI theme...")
load_saved_theme()
# Initialize real-time update manager
print("β‘ Initializing real-time updates...")
update_manager = get_update_manager()
# Create main dashboard
print("π Creating main dashboard...")
dashboard = MainDashboard()
# Connect real-time updates to dashboard
update_manager.new_post_detected.connect(
lambda data: dashboard.activity_feed.add_activity("new_post", f"New post from @{data.get('target_username', 'unknown')}")
)
update_manager.new_follower_detected.connect(
lambda data: dashboard.activity_feed.add_activity("new_follower", f"@{data.get('target_username', 'unknown')} gained a follower")
)
update_manager.system_status_updated.connect(
lambda data: dashboard.system_stats.update_stats()
)
# Start real-time updates
print("π Starting real-time update system...")
update_manager.start()
# Show dashboard
print("β¨ Displaying dashboard...")
dashboard.show()
# Show welcome message
dashboard.show_notification(
"SMSS Dashboard Launched",
"Social Media Surveillance System Phase 5 is now running with full UI integration!",
"info"
)
print("\nπ Dashboard launched successfully!")
print("π Available Features:")
print(" β
Main Dashboard with Real-time Monitoring")
print(" β
Surveillance Panel with Target Management")
print(" β
Analytics Panel with Data Visualization")
print(" β
Settings Panel with Configuration")
print(" β
Notification System with Alerts")
print(" β
Real-time Updates and Background Processing")
print(" β
Modern UI with Light/Dark Theme Support")
print("\nπ‘ Use the dashboard to manage surveillance targets and monitor activity!")
# Start event loop
exit_code = app.exec()
# Cleanup
print("\nπ Shutting down...")
update_manager.stop()
return exit_code
except ImportError as e:
print(f"β UI components not available: {e}")
print("\nοΏ½ Attempting automatic fix...")
# Try automatic PyQt6 fix
if attempt_auto_pyqt_fix():
print("β
Auto-fix successful! Retrying UI launch...")
try:
# Recursive call to retry the UI launch
return launch_ui_dashboard()
except Exception as retry_error:
print(f"β Retry failed: {retry_error}")
print("π‘ Using command-line interface instead:")
return show_cli_menu()
else:
print("β Auto-fix failed. Using command-line interface:")
return show_cli_menu()
except Exception as e:
logger.error(f"Error launching UI dashboard: {e}")
print(f"β Failed to launch dashboard: {e}")
return 1
def show_cli_menu():
"""Show interactive CLI menu when UI is not available"""
try:
print("\n" + "=" * 60)
print("π SMSS Command Line Interface")
print("=" * 60)
print("\nπ Available Operations:")
print(" 1. Test browser engine")
print(" 2. Show system information")
print(" 3. Run comprehensive tests")
print(" 4. Scrape Instagram profile")
print(" 5. Analyze hashtag")
print(" 6. Analyze location")
print(" 7. Start coordinator service")
print(" 8. Show coordinator status")
print(" 9. Run batch operation")
print(" 0. Exit")
print("\nπ‘ Quick Commands:")
print(" python launcher.py --help # Show all options")
print(" python launcher.py --test-browser # Test browser")
print(" python launcher.py --info # System info")
print(" python launcher.py --scrape-profile USER # Scrape profile")
print(" python launcher.py --scrape-hashtag TAG # Analyze hashtag")
print(" python launcher.py --start-coordinator # Start service")
print("\nπ§ To fix UI issues:")
print(" pip uninstall PyQt6 && pip install PyQt6")
print(" # Or install Visual C++ Redistributable on Windows")
print(" # See TROUBLESHOOTING.md for complete solutions")
print(" # See TROUBLESHOOTING.md for detailed solutions")
return 0
except Exception as e:
logger.error(f"Error showing CLI menu: {e}")
return 1
def test_browser_engine():
"""Test the browser engine functionality"""
try:
from core.browser_engine import InstagramBrowser
print("π Testing Social Media Surveillance System - Browser Engine")
print("=" * 60)
# Initialize browser
print("π± Initializing browser engine...")
browser = InstagramBrowser()
# Setup driver
print("π§ Setting up Chrome driver with stealth configuration...")
if not browser.setup_driver():
print("β Failed to setup browser driver")
return False
print("β
Browser driver setup successful")
# Test navigation
print("π Testing navigation to Instagram...")
browser.driver.get("https://www.instagram.com")
# Take screenshot
print("πΈ Taking screenshot...")
screenshot_path = browser.take_screenshot("test_instagram_page.png")
if screenshot_path:
print(f"β
Screenshot saved: {screenshot_path}")
# Test scrolling
print("π Testing page scrolling...")
browser.scroll_page(scrolls=2)
print("β
Scrolling test completed")
print("\nπ Browser engine test completed successfully!")
# Keep browser open for manual inspection
input("\nβΈοΈ Press Enter to close browser and exit...")
return True
except Exception as e:
logger.error(f"Error during browser engine test: {e}")
print(f"β Test failed: {e}")
return False
finally:
# Cleanup
try:
browser.close()
except:
pass
def run_tests():
"""Run comprehensive test suite"""
print("π§ͺ Running Comprehensive Test Suite")
print("=" * 50)
test_results = {}
# Test Phase 2 - Database
try:
print("\nπ Testing Phase 2 - Database & Data Models...")
from test_phase2_database import run_database_tests
test_results['phase2'] = run_database_tests()
except Exception as e:
print(f"β Phase 2 tests failed: {e}")
test_results['phase2'] = False
# Test Phase 3 - Scrapers
try:
print("\nπ·οΈ Testing Phase 3 - Instagram Scrapers...")
from test_phase3_scrapers import run_scraper_tests
test_results['phase3'] = run_scraper_tests()
except Exception as e:
print(f"β Phase 3 tests failed: {e}")
test_results['phase3'] = False
# Test Phase 4 - Analysis
try:
print("\nπ€ Testing Phase 4 - AI Analysis Engine...")
from test_phase4_analysis import run_analysis_tests
test_results['phase4'] = run_analysis_tests()
except Exception as e:
print(f"β Phase 4 tests failed: {e}")
test_results['phase4'] = False
# Test Phase 5 - UI
try:
print("\nπ₯οΈ Testing Phase 5 - PyQt6 Dashboard...")
from test_phase5_ui import run_ui_tests
test_results['phase5'] = run_ui_tests()
except Exception as e:
print(f"β Phase 5 tests failed: {e}")
test_results['phase5'] = False
# Test Phase 7 - Integration
try:
print("\nπ Testing Phase 7 - Complete Integration...")
from test_phase7_integration import run_all_integration_tests
test_results['phase7'] = run_all_integration_tests()
except Exception as e:
print(f"β Phase 7 tests failed: {e}")
test_results['phase7'] = False
# Print overall results
print("\n" + "=" * 70)
print("π COMPREHENSIVE TEST RESULTS:")
print("=" * 70)
for phase, result in test_results.items():
status = "β
PASSED" if result else "β FAILED"
print(f" {phase.upper()}: {status}")
overall_success = all(test_results.values())
if overall_success:
print("\nπ ALL TESTS PASSED! System is ready for production use.")
else:
print("\nβ οΈ Some tests failed. Please review and fix issues before deployment.")
return overall_success
def show_system_info():
"""Show system information and status"""
print("π Social Media Surveillance System - System Information")
print("=" * 60)
# System info
print("π₯οΈ System Information:")
print(f" Python Version: {sys.version}")
print(f" Platform: {sys.platform}")
print(f" Project Root: {project_root}")
# Check dependencies
print("\nπ¦ Dependency Status:")
dependencies = [
("PyQt6", "PyQt6.QtWidgets"),
("Selenium", "selenium"),
("SQLAlchemy", "sqlalchemy"),
("Requests", "requests"),
("Pillow", "PIL"),
("NumPy", "numpy"),
("Pandas", "pandas"),
("Matplotlib", "matplotlib")
]
for name, module in dependencies:
try:
__import__(module)
print(f" β
{name}: Available")
except ImportError:
print(f" β {name}: Not available")
# Check project structure
print("\nπ Project Structure:")
required_dirs = [
"core", "models", "scrapers", "analysis", "ui",
"notifications", "reporting", "security", "data"
]
for dir_name in required_dirs:
dir_path = project_root / dir_name
if dir_path.exists():
print(f" β
{dir_name}/: Present")
else:
print(f" β {dir_name}/: Missing")
# Phase completion status
print("\nπ Phase Completion Status:")
phases = [
("Phase 1", "Browser Engine", "core/browser_engine.py"),
("Phase 2", "Database & Models", "models/instagram_models.py"),
("Phase 3", "Instagram Scrapers", "scrapers/instagram_profile_scraper.py"),
("Phase 4", "AI Analysis", "analysis/deepseek_analyzer.py"),
("Phase 5", "PyQt6 Dashboard", "ui/main_dashboard.py"),
("Phase 7", "Complete Integration", "scrapers/instagram_hashtag_scraper.py")
]
for phase, description, key_file in phases:
file_path = project_root / key_file
if file_path.exists():
print(f" β
{phase}: {description} - Complete")
else:
print(f" β {phase}: {description} - Missing")
def run_headless_mode(args):
"""Run system in headless mode for automation"""
try:
print("π€ Starting headless automation mode...")
print(" This mode runs scrapers without UI for automation purposes")
# This would implement headless automation logic
# For now, just show what would be available
print("\nπ Available headless operations:")
print(" β’ Profile scraping: --scrape-profile USERNAME")
print(" β’ Post scraping: --scrape-posts USERNAME")
print(" β’ Hashtag analysis: --scrape-hashtag HASHTAG")
print(" β’ Location analysis: --scrape-location LOCATION_ID")
print(" β’ Follower tracking: --track-followers USERNAME")
print(" β’ Batch operations: --batch-operation TYPE")
return 0
except Exception as e:
logger.error(f"Error in headless mode: {e}")
return 1
def run_profile_scraping(username: str, args):
"""Run profile scraping for a specific user"""
try:
from scrapers.instagram_profile_scraper import scrape_single_profile
print(f"π€ Scraping profile: @{username}")
print("=" * 50)
# Perform profile scraping
result = scrape_single_profile(username)
if result:
print(f"β
Profile scraping completed for @{username}")
_output_results("profile", result, args.output_format)
return 0
else:
print(f"β Profile scraping failed for @{username}")
return 1
except Exception as e:
logger.error(f"Error scraping profile {username}: {e}")
print(f"β Error: {e}")
return 1
def run_post_scraping(username: str, args):
"""Run post scraping for a specific user"""
try:
from scrapers.instagram_post_scraper import scrape_user_posts_quick
print(f"π Scraping posts from: @{username}")
print(f" Max posts: {args.max_items}")
print("=" * 50)
# Perform post scraping
result = scrape_user_posts_quick(username, args.max_items)
if result and result.get('status') == 'completed':
print(f"β
Post scraping completed for @{username}")
print(f" Posts scraped: {len(result.get('posts_scraped', []))}")
_output_results("posts", result, args.output_format)
return 0
else:
print(f"β Post scraping failed for @{username}")
return 1
except Exception as e:
logger.error(f"Error scraping posts for {username}: {e}")
print(f"β Error: {e}")
return 1
def run_hashtag_analysis(hashtag: str, args):
"""Run hashtag analysis"""
try:
from scrapers.instagram_hashtag_scraper import analyze_hashtag_quick
print(f"π·οΈ Analyzing hashtag: #{hashtag}")
print(f" Max posts: {args.max_items}")
print("=" * 50)
# Perform hashtag analysis
result = analyze_hashtag_quick(hashtag, args.max_items)
if result and result.get('status') == 'completed':
print(f"β
Hashtag analysis completed for #{hashtag}")
print(f" Post count: {result.get('post_count', 0)}")
print(f" Trending score: {result.get('trending_score', 0):.2f}")
_output_results("hashtag", result, args.output_format)
return 0
else:
print(f"β Hashtag analysis failed for #{hashtag}")
return 1
except Exception as e:
logger.error(f"Error analyzing hashtag {hashtag}: {e}")
print(f"β Error: {e}")
return 1
def run_location_analysis(location_id: str, args):
"""Run location analysis"""
try:
from scrapers.instagram_location_scraper import analyze_location_quick
print(f"π Analyzing location: {location_id}")
print(f" Max posts: {args.max_items}")
print("=" * 50)
# Perform location analysis
result = analyze_location_quick(location_id, args.max_items)
if result and result.get('status') == 'completed':
print(f"β
Location analysis completed for {location_id}")
print(f" Location: {result.get('location_name', 'Unknown')}")
print(f" Post count: {result.get('post_count', 0)}")
print(f" Popularity score: {result.get('popularity_score', 0):.2f}")
_output_results("location", result, args.output_format)
return 0
else:
print(f"β Location analysis failed for {location_id}")
return 1
except Exception as e:
logger.error(f"Error analyzing location {location_id}: {e}")
print(f"β Error: {e}")
return 1
def run_follower_tracking(username: str, args):
"""Run follower tracking for a specific user"""
try:
from scrapers.follower_tracker import track_followers_quick
print(f"π₯ Tracking followers for: @{username}")
print(f" Max followers: {args.max_items}")
print("=" * 50)
# Perform follower tracking
result = track_followers_quick(username, args.max_items)
if result and result.get('status') == 'completed':
print(f"β
Follower tracking completed for @{username}")
print(f" New followers: {len(result.get('new_followers', []))}")
print(f" Unfollowed: {len(result.get('unfollowed_users', []))}")
_output_results("followers", result, args.output_format)
return 0
else:
print(f"β Follower tracking failed for @{username}")
return 1
except Exception as e:
logger.error(f"Error tracking followers for {username}: {e}")
print(f"β Error: {e}")
return 1
def run_batch_operation(operation_type: str, args):
"""Run batch operations on multiple targets using coordinator"""
try:
from core.scraper_coordinator import coordinator, ScraperType, TaskPriority
print(f"π Running batch {operation_type} operation with intelligent coordination")
print("=" * 70)
# Map operation types to scraper types
scraper_type_map = {
'profiles': ScraperType.PROFILE,
'posts': ScraperType.POSTS,
'hashtags': ScraperType.HASHTAGS,
'locations': ScraperType.LOCATIONS,
'followers': ScraperType.FOLLOWERS
}
if operation_type not in scraper_type_map:
print(f"β Unknown operation type: {operation_type}")
return 1
scraper_type = scraper_type_map[operation_type]
# Get targets from database or use demo targets
targets = _get_batch_targets(operation_type)
if not targets:
print(f"β No targets found for {operation_type} operation")
return 1
print(f"π Found {len(targets)} targets for processing")
print(f"π€ Starting coordinator...")
# Start coordinator
coordinator.start()
# Add tasks to coordinator
task_ids = []
for target in targets:
task_id = coordinator.add_task(
scraper_type=scraper_type,
target=target,
priority=TaskPriority.NORMAL,
max_items=args.max_items
)
task_ids.append(task_id)
print(f" β
Queued task for {target}: {task_id}")
print(f"\nβ³ Processing {len(task_ids)} tasks...")
print(" Use Ctrl+C to stop and view results")
# Monitor progress
completed_count = 0
try:
while completed_count < len(task_ids):
time.sleep(5)
# Check task statuses
new_completed = 0
for task_id in task_ids:
status = coordinator.get_task_status(task_id)
if status and status['status'] in ['completed', 'failed']:
new_completed += 1
if new_completed > completed_count:
completed_count = new_completed
print(f" π Progress: {completed_count}/{len(task_ids)} tasks completed")
# Show coordinator stats
stats = coordinator.get_statistics()
print(f" π Active: {stats['active_tasks']}, Pending: {stats['pending_tasks']}")
except KeyboardInterrupt:
print("\nβΉοΈ Stopping batch operation...")
# Stop coordinator
coordinator.stop()
# Generate summary report
_generate_batch_report(task_ids, operation_type, args.output_format)
return 0
except Exception as e:
logger.error(f"Error in batch operation {operation_type}: {e}")
print(f"β Error: {e}")
return 1
def _get_batch_targets(operation_type: str) -> List[str]:
"""Get targets for batch operation"""
try:
from core.data_manager import data_manager
if operation_type == 'profiles':
# Get surveillance targets from database
targets = data_manager.get_all_surveillance_targets()
return [target.instagram_username for target in targets[:10]] # Limit for demo
elif operation_type == 'hashtags':
# Demo hashtags
return ['photography', 'travel', 'food', 'fashion', 'technology']
elif operation_type == 'locations':
# Demo location IDs (major cities)
return ['213385402', '212988663', '213570652'] # NYC, LA, London
else:
# For posts and followers, use surveillance targets
targets = data_manager.get_all_surveillance_targets()
return [target.instagram_username for target in targets[:5]] # Limit for demo
except Exception as e:
logger.error(f"Error getting batch targets: {e}")
return []
def _generate_batch_report(task_ids: List[str], operation_type: str, output_format: str):
"""Generate batch operation report"""
try:
from core.scraper_coordinator import coordinator
print(f"\nπ Generating {operation_type} batch report...")
# Collect results
results = []
for task_id in task_ids:
status = coordinator.get_task_status(task_id)
if status:
results.append(status)
# Summary statistics
completed = sum(1 for r in results if r['status'] == 'completed')
failed = sum(1 for r in results if r['status'] == 'failed')
print(f"π Batch Operation Summary:")
print(f" Total tasks: {len(task_ids)}")
print(f" Completed: {completed}")
print(f" Failed: {failed}")
print(f" Success rate: {(completed/len(task_ids)*100):.1f}%")
# Coordinator statistics
stats = coordinator.get_statistics()
print(f"\nπ€ Coordinator Statistics:")
print(f" Conflicts avoided: {stats['conflicts_avoided']}")
print(f" Rate limits respected: {stats['rate_limits_respected']}")
print(f" Average execution time: {stats['average_execution_time']:.1f}s")
# Save detailed report if requested
if output_format == 'json':
import json
report_file = f"batch_{operation_type}_report.json"
with open(report_file, 'w') as f:
json.dump({
'operation_type': operation_type,
'summary': {
'total_tasks': len(task_ids),
'completed': completed,
'failed': failed,
'success_rate': completed/len(task_ids)*100
},
'coordinator_stats': stats,
'task_results': results
}, f, indent=2, default=str)
print(f"π Detailed report saved to: {report_file}")
except Exception as e:
logger.error(f"Error generating batch report: {e}")
print(f"β Error generating report: {e}")
def start_coordinator_service():
"""Start the scraper coordinator as a background service"""
try:
from core.scraper_coordinator import coordinator
print("π€ Starting Scraper Coordinator Service")
print("=" * 50)
# Start coordinator
coordinator.start()
print("β
Coordinator service started successfully")
print("π Service Features:")
print(" β’ Intelligent task scheduling")
print(" β’ Conflict avoidance between scrapers")
print(" β’ Rate limit management")
print(" β’ Browser resource pooling")
print(" β’ Automatic retry logic")
print(f"\nπ Coordinator is running with:")
print(f" β’ Max concurrent tasks: {coordinator.max_concurrent_tasks}")
print(f" β’ Browser pool size: {coordinator.max_browser_instances}")
print(f"\nπ‘ Use --coordinator-status to check status")
print(f"π‘ Use --batch-operation to submit batch jobs")
print(f"π‘ Press Ctrl+C to stop the service")
# Keep service running
try:
while True:
time.sleep(10)
stats = coordinator.get_statistics()
if stats['active_tasks'] > 0 or stats['pending_tasks'] > 0:
print(f"π Active: {stats['active_tasks']}, Pending: {stats['pending_tasks']}")
except KeyboardInterrupt:
print("\nβΉοΈ Stopping coordinator service...")
coordinator.stop()
print("β
Coordinator service stopped")
return 0
except Exception as e:
logger.error(f"Error starting coordinator service: {e}")
print(f"β Error: {e}")
return 1
def show_coordinator_status():
"""Show coordinator status and statistics"""
try:
from core.scraper_coordinator import coordinator
print("π Scraper Coordinator Status")
print("=" * 40)
# Get statistics
stats = coordinator.get_statistics()
print(f"π Task Status:")
print(f" Active tasks: {stats['active_tasks']}")
print(f" Pending tasks: {stats['pending_tasks']}")
print(f" Completed tasks: {stats['completed_tasks']}")
print(f"\nπ Performance:")
print(f" Tasks completed: {stats['tasks_completed']}")
print(f" Tasks failed: {stats['tasks_failed']}")
print(f" Average execution time: {stats['average_execution_time']:.1f}s")
print(f"\nπ‘οΈ Protection:")
print(f" Conflicts avoided: {stats['conflicts_avoided']}")
print(f" Rate limits respected: {stats['rate_limits_respected']}")
print(f"\nπ₯οΈ Resources:")
print(f" Available browsers: {stats['available_browsers']}")
print(f" Browser pool size: {coordinator.max_browser_instances}")
# Calculate success rate
total_tasks = stats['tasks_completed'] + stats['tasks_failed']
if total_tasks > 0:
success_rate = (stats['tasks_completed'] / total_tasks) * 100
print(f"\nβ
Success rate: {success_rate:.1f}%")
# Show recent task history
print(f"\nπ Recent Tasks:")
recent_tasks = coordinator.task_history[-5:] if coordinator.task_history else []
for task in recent_tasks:
status_emoji = "β
" if task.status.value == "completed" else "β"
print(f" {status_emoji} {task.scraper_type.value}: {task.target} ({task.status.value})")
if not recent_tasks:
print(" No recent tasks")
return 0
except Exception as e:
logger.error(f"Error showing coordinator status: {e}")
print(f"β Error: {e}")
return 1
def _output_results(result_type: str, data: dict, output_format: str):
"""Output results in specified format"""
try:
if output_format == "console":
print(f"\nπ {result_type.title()} Results:")
print("-" * 30)
for key, value in data.items():
if isinstance(value, (list, dict)):
print(f" {key}: {len(value) if isinstance(value, list) else 'object'}")
else:
print(f" {key}: {value}")
elif output_format == "json":
import json
output_file = f"{result_type}_results.json"
with open(output_file, 'w') as f:
json.dump(data, f, indent=2, default=str)
print(f"π Results saved to: {output_file}")
elif output_format == "csv":
print(f"π CSV output for {result_type} would be implemented here")
except Exception as e:
logger.error(f"Error outputting results: {e}")
def main():
"""Main entry point with command line argument support"""
parser = argparse.ArgumentParser(
description="Social Media Surveillance System - Phase 5 Complete",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python launcher.py # Launch full UI dashboard
python launcher.py --test-browser # Test browser engine only
python launcher.py --run-tests # Run comprehensive test suite
python launcher.py --info # Show system information
python launcher.py --scrape-profile username # Scrape specific profile
python launcher.py --scrape-posts username # Scrape posts from profile
python launcher.py --scrape-hashtag travel # Analyze hashtag
python launcher.py --scrape-location 123456 # Analyze location
python launcher.py --track-followers username # Track follower changes
python launcher.py --batch-operation profiles # Run batch profile scraping
python launcher.py --headless # Run in automation mode
"""
)
parser.add_argument(
"--test-browser",
action="store_true",
help="Test browser engine functionality only"
)
parser.add_argument(
"--run-tests",
action="store_true",
help="Run comprehensive test suite for all phases"
)
parser.add_argument(
"--info",
action="store_true",
help="Show system information and status"
)
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode (no UI)"
)
parser.add_argument(
"--scrape-profile",
type=str,
help="Scrape a specific Instagram profile (username)"
)
parser.add_argument(
"--scrape-posts",
type=str,
help="Scrape posts from a specific Instagram profile (username)"
)
parser.add_argument(
"--scrape-hashtag",
type=str,
help="Analyze a specific hashtag (without # symbol)"
)
parser.add_argument(
"--scrape-location",
type=str,
help="Analyze a specific location (location ID)"
)
parser.add_argument(
"--track-followers",
type=str,
help="Track followers for a specific profile (username)"
)
parser.add_argument(
"--batch-operation",
type=str,
choices=["profiles", "posts", "hashtags", "locations", "followers"],
help="Run batch operation on multiple targets"
)
parser.add_argument(
"--max-items",
type=int,
default=50,
help="Maximum number of items to process (default: 50)"
)
parser.add_argument(
"--output-format",
type=str,
choices=["json", "csv", "console"],
default="console",
help="Output format for results (default: console)"
)
parser.add_argument(
"--start-coordinator",
action="store_true",
help="Start the scraper coordinator as a background service"
)
parser.add_argument(
"--coordinator-status",
action="store_true",
help="Show coordinator status and statistics"
)
args = parser.parse_args()
# Print header
print("π Social Media Surveillance System")
print("π€ AI-Powered Instagram Monitoring - Phase 5 Complete")
print("=" * 60)
try:
if args.info:
show_system_info()
return 0
elif args.test_browser:
print("π§ͺ Running Browser Engine Test...")
success = test_browser_engine()
return 0 if success else 1
elif args.run_tests:
print("π§ͺ Running Comprehensive Test Suite...")
success = run_tests()
return 0 if success else 1
elif args.headless: