forked from vara-prasad-07/Group_AC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserdata_manager.py
More file actions
197 lines (152 loc) · 6.4 KB
/
Copy pathuserdata_manager.py
File metadata and controls
197 lines (152 loc) · 6.4 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
import json
import re
from typing import Optional, Dict, Any
from pathlib import Path
class UserDataManager:
"""
Manages user data from userdata.json.
Handles loading, querying, and formatting user information.
"""
def __init__(self, filepath: str = "userdata.json"):
"""
Initialize UserDataManager and load user data.
Args:
filepath: Path to userdata.json file
"""
self.filepath = filepath
self.users_data = {}
self.load_data()
def load_data(self):
"""Load user data from JSON file."""
try:
if not Path(self.filepath).exists():
print(f"⚠️ UserData file not found at {self.filepath}")
self.users_data = {}
return
with open(self.filepath, 'r') as f:
data = json.load(f)
# Create a phone number index for fast lookup
self.users_data = {}
if "users" in data and isinstance(data["users"], list):
for user in data["users"]:
phone = user.get("phone_number", "").strip()
if phone:
self.users_data[phone] = user
print(f"✓ Loaded {len(self.users_data)} users from {self.filepath}")
else:
print(f"⚠️ Invalid userdata.json format")
except json.JSONDecodeError as e:
print(f"❌ Error parsing {self.filepath}: {e}")
self.users_data = {}
except Exception as e:
print(f"❌ Error loading user data: {e}")
self.users_data = {}
def extract_phone_number(self, text: str) -> Optional[str]:
"""
Extract phone number from various formats.
Handles formats like +919876543210, 9876543210, +91-98765-43210, etc.
Args:
text: Text that may contain a phone number
Returns:
Normalized phone number (+91...) or None
"""
if not text:
return None
# Remove common separators and spaces
cleaned = re.sub(r'[\s\-\(\)\.]+', '', text)
# Try to find 10-digit number (Indian format)
match = re.search(r'(\d{10})$', cleaned)
if match:
return "+91" + match.group(1)
# Try to find 12-digit number starting with 91
match = re.search(r'91(\d{10})', cleaned)
if match:
return "+91" + match.group(1)
# Try to find number starting with +91
match = re.search(r'(\+91\d{10})', cleaned)
if match:
return match.group(1)
return None
def get_user_by_phone(self, phone_number: Optional[str]) -> Optional[Dict[str, Any]]:
"""
Get user data by phone number.
Args:
phone_number: Phone number in any format
Returns:
User data dict or None if not found
"""
if not phone_number:
return None
# Normalize the phone number
normalized = self.extract_phone_number(phone_number)
if not normalized:
return None
user = self.users_data.get(normalized)
if user:
print(f"✓ Found user: {user.get('name')} ({normalized})")
else:
print(f"⚠️ User not found for: {normalized}")
return user
def format_user_context(self, user_data: Optional[Dict[str, Any]]) -> str:
"""
Format user data into readable context for the LLM.
Args:
user_data: User data dict from userdata.json
Returns:
Formatted string with user information
"""
if not user_data:
return ""
context = "\n=== CUSTOMER ACCOUNT INFO ===\n"
context += f"Name: {user_data.get('name', 'N/A')}\n"
context += f"Phone: {user_data.get('phone_number', 'N/A')}\n"
context += f"Current Balance: ₹{user_data.get('current_balance', 0)}\n"
context += f"Recharge Plan: {user_data.get('recharge_plan', 'N/A')}\n"
context += f"Data Left: {user_data.get('data_left', 'N/A')}\n"
context += f"Plan Validity: {user_data.get('validity', 'N/A')}\n"
context += f"Last Recharge: {user_data.get('last_recharge_date', 'N/A')} (₹{user_data.get('last_recharge_amount', 0)})\n"
context += f"Talktime Balance: ₹{user_data.get('talktime_balance', 0)}\n"
context += f"SMS Balance: {user_data.get('sms_balance', 0)} SMS\n"
active_services = user_data.get('active_services', [])
if active_services:
context += f"Active Services: {', '.join(active_services)}\n"
context += f"Upcoming Bill Date: {user_data.get('upcoming_bill_date', 'N/A')}\n"
context += "=== END ACCOUNT INFO ===\n"
return context
# Global instance for easy access
_user_manager = None
def get_user_manager() -> UserDataManager:
"""Get or create the global UserDataManager instance."""
global _user_manager
if _user_manager is None:
_user_manager = UserDataManager()
return _user_manager
def get_user_by_phone(phone_number: Optional[str]) -> Optional[Dict[str, Any]]:
"""Convenience function to get user by phone number."""
return get_user_manager().get_user_by_phone(phone_number)
def format_user_context(user_data: Optional[Dict[str, Any]]) -> str:
"""Convenience function to format user context."""
return get_user_manager().format_user_context(user_data)
def extract_phone_number(text: str) -> Optional[str]:
"""Convenience function to extract phone number."""
return get_user_manager().extract_phone_number(text)
if __name__ == "__main__":
# Test the manager
manager = UserDataManager()
# Test phone number extraction
test_phones = [
"9876543210",
"+919876543210",
"+91-98765-43210",
"919876543210",
"From +91 9876543210"
]
print("\n📱 Testing phone number extraction:")
for test in test_phones:
extracted = manager.extract_phone_number(test)
print(f" '{test}' → {extracted}")
# Test user lookup
print("\n🔍 Testing user lookup:")
user = manager.get_user_by_phone("+919876543210")
if user:
print(manager.format_user_context(user))