Spaces:
Sleeping
Sleeping
Download visitor_tracker.py from dixitramjendra/MACD_Strategy: direct link, hf CLI and curl.
- Browser
- Download file 8.37 kB
-
https://huggingface.co/spaces/dixitramjendra/MACD_Strategy/resolve/main/visitor_tracker.py
- Command line
-
hf download hf://spaces/dixitramjendra/MACD_Strategy/visitor_tracker.py
-
curl -L -o visitor_tracker.py https://huggingface.co/spaces/dixitramjendra/MACD_Strategy/resolve/main/visitor_tracker.py
8.37 kB
| #!/usr/bin/env python3 | |
| """ | |
| Visitor Tracker - Track unique visitors by IP address | |
| Stores visitor data with timestamps and provides analytics | |
| """ | |
| import json | |
| import hashlib | |
| from datetime import datetime, timedelta | |
| from pathlib import Path | |
| from typing import Dict, List, Optional | |
| class VisitorTracker: | |
| def __init__(self, data_file: str = "visitors.json"): | |
| self.data_file = Path(data_file) | |
| self.data = self._load_data() | |
| def _load_data(self) -> Dict: | |
| """Load visitor data from JSON file""" | |
| if self.data_file.exists(): | |
| try: | |
| with open(self.data_file, 'r') as f: | |
| return json.load(f) | |
| except Exception as e: | |
| print(f"Error loading visitor data: {e}") | |
| return self._init_data() | |
| return self._init_data() | |
| def _init_data(self) -> Dict: | |
| """Initialize empty visitor data structure""" | |
| return { | |
| "visitors": {}, | |
| "total_visits": 0, | |
| "unique_visitors": 0, | |
| "daily_stats": {} | |
| } | |
| def _save_data(self): | |
| """Save visitor data to JSON file""" | |
| try: | |
| with open(self.data_file, 'w') as f: | |
| json.dump(self.data, f, indent=2, default=str) | |
| except Exception as e: | |
| print(f"Error saving visitor data: {e}") | |
| def _hash_ip(self, ip: str) -> str: | |
| """Hash IP address for privacy (optional)""" | |
| # For now, store full IP. Can enable hashing later for privacy | |
| return ip | |
| # return hashlib.sha256(ip.encode()).hexdigest()[:16] | |
| def track_visit(self, ip: str, user_agent: str = "", country: str = "") -> Dict: | |
| """ | |
| Track a visitor visit | |
| Returns: visitor statistics | |
| """ | |
| ip_hash = self._hash_ip(ip) | |
| now = datetime.now() | |
| today = now.strftime("%Y-%m-%d") | |
| # Initialize daily stats if needed | |
| if today not in self.data["daily_stats"]: | |
| self.data["daily_stats"][today] = { | |
| "visits": 0, | |
| "unique_visitors": set(), | |
| "new_visitors": 0 | |
| } | |
| # Track visitor | |
| is_new_visitor = ip_hash not in self.data["visitors"] | |
| if is_new_visitor: | |
| self.data["visitors"][ip_hash] = { | |
| "ip": ip, | |
| "first_visit": now.isoformat(), | |
| "last_visit": now.isoformat(), | |
| "visit_count": 1, | |
| "user_agent": user_agent, | |
| "country": country | |
| } | |
| self.data["unique_visitors"] += 1 | |
| self.data["daily_stats"][today]["new_visitors"] += 1 | |
| else: | |
| visitor = self.data["visitors"][ip_hash] | |
| visitor["last_visit"] = now.isoformat() | |
| visitor["visit_count"] += 1 | |
| if user_agent: | |
| visitor["user_agent"] = user_agent | |
| # Update totals | |
| self.data["total_visits"] += 1 | |
| self.data["daily_stats"][today]["visits"] += 1 | |
| # Convert set to list for JSON serialization | |
| if isinstance(self.data["daily_stats"][today]["unique_visitors"], set): | |
| self.data["daily_stats"][today]["unique_visitors"] = list( | |
| self.data["daily_stats"][today]["unique_visitors"] | |
| ) | |
| if ip_hash not in self.data["daily_stats"][today]["unique_visitors"]: | |
| self.data["daily_stats"][today]["unique_visitors"].append(ip_hash) | |
| self._save_data() | |
| return self.get_stats() | |
| def get_stats(self) -> Dict: | |
| """Get current visitor statistics""" | |
| now = datetime.now() | |
| active_threshold = now - timedelta(minutes=30) | |
| # Count active visitors (visited in last 30 minutes) | |
| active_count = 0 | |
| for visitor in self.data["visitors"].values(): | |
| try: | |
| last_visit = datetime.fromisoformat(visitor["last_visit"]) | |
| if last_visit >= active_threshold: | |
| active_count += 1 | |
| except: | |
| pass | |
| today = now.strftime("%Y-%m-%d") | |
| today_stats = self.data["daily_stats"].get(today, { | |
| "visits": 0, | |
| "unique_visitors": [], | |
| "new_visitors": 0 | |
| }) | |
| return { | |
| "total_visits": self.data["total_visits"], | |
| "unique_visitors": self.data["unique_visitors"], | |
| "active_visitors": active_count, | |
| "today_visits": today_stats["visits"], | |
| "today_unique": len(today_stats.get("unique_visitors", [])), | |
| "today_new": today_stats.get("new_visitors", 0) | |
| } | |
| def get_daily_report_data(self, date: Optional[str] = None) -> Dict: | |
| """ | |
| Get detailed visitor data for daily report | |
| date: YYYY-MM-DD format, defaults to today | |
| """ | |
| if date is None: | |
| date = datetime.now().strftime("%Y-%m-%d") | |
| stats = self.data["daily_stats"].get(date, { | |
| "visits": 0, | |
| "unique_visitors": [], | |
| "new_visitors": 0 | |
| }) | |
| # Get visitor details for the day | |
| visitor_details = [] | |
| unique_ips = stats.get("unique_visitors", []) | |
| for ip_hash in unique_ips: | |
| if ip_hash in self.data["visitors"]: | |
| visitor = self.data["visitors"][ip_hash] | |
| visitor_details.append({ | |
| "ip": visitor["ip"], | |
| "visit_count": visitor["visit_count"], | |
| "last_visit": visitor["last_visit"], | |
| "user_agent": visitor.get("user_agent", "Unknown") | |
| }) | |
| # Sort by visit count | |
| visitor_details.sort(key=lambda x: x["visit_count"], reverse=True) | |
| return { | |
| "date": date, | |
| "total_visits": stats["visits"], | |
| "unique_visitors": len(unique_ips), | |
| "new_visitors": stats.get("new_visitors", 0), | |
| "returning_visitors": len(unique_ips) - stats.get("new_visitors", 0), | |
| "visitor_details": visitor_details, | |
| "all_time_total": self.data["total_visits"], | |
| "all_time_unique": self.data["unique_visitors"] | |
| } | |
| def cleanup_old_data(self, days_to_keep: int = 90): | |
| """Remove visitor data older than specified days""" | |
| cutoff_date = datetime.now() - timedelta(days=days_to_keep) | |
| # Remove old daily stats | |
| dates_to_remove = [] | |
| for date_str in self.data["daily_stats"].keys(): | |
| try: | |
| date = datetime.strptime(date_str, "%Y-%m-%d") | |
| if date < cutoff_date: | |
| dates_to_remove.append(date_str) | |
| except: | |
| pass | |
| for date_str in dates_to_remove: | |
| del self.data["daily_stats"][date_str] | |
| # Remove visitors who haven't visited in the retention period | |
| visitors_to_remove = [] | |
| for ip_hash, visitor in self.data["visitors"].items(): | |
| try: | |
| last_visit = datetime.fromisoformat(visitor["last_visit"]) | |
| if last_visit < cutoff_date: | |
| visitors_to_remove.append(ip_hash) | |
| except: | |
| pass | |
| for ip_hash in visitors_to_remove: | |
| del self.data["visitors"][ip_hash] | |
| if visitors_to_remove or dates_to_remove: | |
| self._save_data() | |
| print(f"Cleaned up {len(visitors_to_remove)} old visitors and {len(dates_to_remove)} old daily stats") | |
| if __name__ == "__main__": | |
| # Test the tracker | |
| tracker = VisitorTracker() | |
| # Simulate some visits | |
| print("Simulating visits...") | |
| tracker.track_visit("192.168.1.1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "US") | |
| tracker.track_visit("192.168.1.2", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0)", "IN") | |
| tracker.track_visit("192.168.1.1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "US") # Repeat visitor | |
| # Get stats | |
| stats = tracker.get_stats() | |
| print("\nCurrent Stats:") | |
| print(json.dumps(stats, indent=2)) | |
| # Get daily report | |
| report = tracker.get_daily_report_data() | |
| print("\nDaily Report:") | |
| print(json.dumps(report, indent=2)) | |