-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
201 lines (175 loc) · 7.95 KB
/
main.py
File metadata and controls
201 lines (175 loc) · 7.95 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
from src.coordinator_agent import CoordinatorAgent
from src.database import Database
from data_processing.cluster_for_users import optimal_clustering
from utils.utils import MatchArrangementResult
from datetime import datetime
import json
from src.match_exception import MatchFailedException
def convert_match_plan_to_create_format(match_setup):
"""
Convert CoordinatorAnswer (dict or Pydantic model) to the format expected by create_match.
Args:
match_setup: CoordinatorAnswer object (dict or Pydantic model)
Returns:
dict with participants, field, scheduledDateTime
"""
# Handle both dict and Pydantic model inputs
if isinstance(match_setup, dict):
teams = match_setup.get("teams", [])
date_str = match_setup.get("date")
time_str = match_setup.get("time")
pitch = match_setup.get("pitch")
else:
# Pydantic model
teams = match_setup.teams
date_str = match_setup.date
time_str = match_setup.time
pitch = match_setup.pitch
# Extract all player IDs from teams
participants = []
for team in teams:
# Handle both dict and object access
if isinstance(team, dict):
players = team.get("players", [])
else:
players = team.players
for player in players:
# Handle both dict and object access
if isinstance(player, dict):
player_id = player.get("id")
else:
player_id = player.id
participants.append(str(player_id))
# Combine date and time into scheduledDateTime
# Parse date and time into datetime object
try:
# Assuming date is in YYYY-MM-DD format and time is in HH:MM format
datetime_str = f"{date_str} {time_str}"
scheduled_dt = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
# Check if date is in the past - if so, adjust to next occurrence
now = datetime.now()
if scheduled_dt < now:
print(f"Warning: Date {date_str} {time_str} is in the past. Adjusting to next week...")
# Add 7 days to make it in the future
from datetime import timedelta
days_ahead = 7
scheduled_dt = scheduled_dt + timedelta(days=days_ahead)
# Keep adding weeks until it's in the future
while scheduled_dt < now:
scheduled_dt = scheduled_dt + timedelta(days=7)
print(f"Adjusted date to: {scheduled_dt.strftime('%Y-%m-%d %H:%M')}")
except ValueError:
# Fallback: try ISO format or use future datetime
try:
scheduled_dt = datetime.fromisoformat(f"{date_str}T{time_str}")
# Check if in past
if scheduled_dt < datetime.now():
from datetime import timedelta
scheduled_dt = scheduled_dt + timedelta(days=7)
while scheduled_dt < datetime.now():
scheduled_dt = scheduled_dt + timedelta(days=7)
except:
print(f"Warning: Could not parse date/time '{date_str}' '{time_str}', using future datetime")
# Use tomorrow at the same time
from datetime import timedelta
scheduled_dt = datetime.now() + timedelta(days=1)
if time_str:
try:
hour, minute = map(int, time_str.split(':'))
scheduled_dt = scheduled_dt.replace(hour=hour, minute=minute, second=0, microsecond=0)
except:
pass
return {
"participants": participants,
"field": pitch,
"scheduledDateTime": scheduled_dt.isoformat()
}
def main():
# 1. Load the agent and the data
print("Starting the matchmaking coordinator...")
agent = CoordinatorAgent()
print("Initializing database API client...")
db = Database()
print("Database client ready (using server API endpoints)")
num_people = 10
print("Started the matchmaking...")
import time
# 2.1 Fetch users from the database via API
print("Fetching users from API...")
try:
users = db.get_n_users(num_users=100, collection="test/profiles")
print(f"Successfully fetched {len(users)} users from API")
except Exception as e:
print(f"Error fetching users from API: {e}")
print("Falling back to mock data...")
# Fallback to mock data if API fails
try:
with open("mock_data/users.json", "r") as f:
users = json.load(f).get("users", [])
print(f"Loaded {len(users)} users from mock data")
except Exception as mock_error:
print(f"Failed to load mock data: {mock_error}")
print("Waiting 5 seconds before retrying...")
time.sleep(5)
if not users:
print("No users available. Waiting 5 seconds before retrying...")
time.sleep(5)
# 2.2 Perform clustering and get centers
print(f"Performing clustering on {len(users)} users...")
try:
centers = optimal_clustering(users,
people_per_cluster=40,
max_clusters=15)
print(f"Clustering completed. Found {len(centers)} cluster centers")
except ValueError as e:
print(f"Clustering error: {e}")
print("Waiting before retrying...")
time.sleep(5)
if not centers:
print("No cluster centers found. Skipping this iteration.")
time.sleep(5)
# 2.3 For each center take users and organise matches
print(f"Processing {len(centers)} cluster center(s)...")
for center_idx, center in enumerate(centers, 1):
print(f"\nProcessing cluster center {center_idx}/{len(centers)} at ({center[0]:.4f}, {center[1]:.4f})")
# center is a tuple (latitude, longitude) from clustering
latitude, longitude = center
# Get users in the location for this cluster center
print(f"Fetching users within 15km radius...")
try:
cluster_users = db.get_users_in_location(latitude, longitude, radius_km=15)
print(f"Found {len(cluster_users)} users for this center")
except Exception as e:
print(f"Error fetching users for center: {e}")
print(f"Using all users from clustering instead ({len(users)} users)")
cluster_users = users
if not cluster_users:
print(f"No users found for center {center}. Skipping to next center.")
continue
# Provide users to the agent
print(f"Providing {len(cluster_users)} users to coordinator agent...")
agent.provide_users(cluster_users)
print("Running matchmaking algorithm...")
match_result, match_setup = agent.run(num_people=num_people,
slot=(None, None),
cluster_center=center)
print(f"Matchmaking result: {match_result}")
# Only create match if successful
if match_result == MatchArrangementResult.MATCH and match_setup:
print("Match arrangement successful! Converting to API format...")
# Convert CoordinatorAnswer to create_match format
match_plan_dict = convert_match_plan_to_create_format(match_setup)
print(f"Match plan: {len(match_plan_dict.get('participants', []))} participants, field: {match_plan_dict.get('field')}")
try:
match_id = db.create_match(match_plan=match_plan_dict, cluster_center=center)
print(f"✓✓✓ Successfully created match with ID: {match_id}")
except Exception as e:
print(f"Error creating match: {e}")
import traceback
traceback.print_exc()
else:
print(f"Match arrangement result: {match_result}")
print("\nCycle completed. Starting next iteration in 5 seconds...\n")
time.sleep(5)
if __name__ == "__main__":
main()