forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapped.py
More file actions
223 lines (172 loc) · 5.77 KB
/
Copy pathwrapped.py
File metadata and controls
223 lines (172 loc) · 5.77 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
"""
Database operations for Wrapped (yearly recap) stored in users/{uid}/wrapped/{year}.
"""
from datetime import datetime, timezone
from typing import Any, Dict, Optional, cast
from ._client import db
# Collection name under user document
WRAPPED_COLLECTION = 'wrapped'
class WrappedStatus:
NOT_GENERATED = 'not_generated'
PROCESSING = 'processing'
DONE = 'done'
ERROR = 'error'
def _typed_doc(doc: Any) -> Dict[str, Any]:
raw: object = doc.to_dict()
return cast(Dict[str, Any], raw) if isinstance(raw, dict) else {}
def _coerce_timestamp(value: Any) -> Optional[datetime]:
if hasattr(value, 'timestamp'):
return datetime.fromtimestamp(value.timestamp(), tz=timezone.utc)
if isinstance(value, datetime):
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
return None
def get_wrapped(uid: str, year: int) -> Optional[Dict[str, Any]]:
"""
Get the wrapped document for a user and year.
Args:
uid: User ID
year: Year (e.g., 2025)
Returns:
Wrapped document data or None if not found
"""
user_ref = db.collection('users').document(uid)
wrapped_ref = user_ref.collection(WRAPPED_COLLECTION).document(str(year))
doc = wrapped_ref.get()
if not getattr(doc, "exists", False):
return None
data = _typed_doc(doc)
# Convert Firestore timestamps to datetime objects
for field in ['started_at', 'completed_at', 'updated_at']:
if field in data and data[field]:
coerced = _coerce_timestamp(data[field])
if coerced is not None:
data[field] = coerced
return data
def create_wrapped(uid: str, year: int) -> Dict[str, Any]:
"""
Create a new wrapped document with status=processing.
Args:
uid: User ID
year: Year (e.g., 2025)
Returns:
The created wrapped document data
"""
now = datetime.now(timezone.utc)
wrapped_data: Dict[str, Any] = {
'year': year,
'status': WrappedStatus.PROCESSING,
'started_at': now,
'updated_at': now,
'completed_at': None,
'result': None,
'error': None,
'schema_version': 1,
}
user_ref = db.collection('users').document(uid)
wrapped_ref = user_ref.collection(WRAPPED_COLLECTION).document(str(year))
wrapped_ref.set(wrapped_data)
return wrapped_data
def update_wrapped_status(
uid: str,
year: int,
status: str,
result: Optional[Dict[str, Any]] = None,
error: Optional[str] = None,
) -> bool:
"""
Update the status of a wrapped document.
Args:
uid: User ID
year: Year (e.g., 2025)
status: New status (processing, done, error)
result: Result payload (only when status=done)
error: Error message (only when status=error)
Returns:
True if updated successfully
"""
user_ref = db.collection('users').document(uid)
wrapped_ref = user_ref.collection(WRAPPED_COLLECTION).document(str(year))
if not getattr(wrapped_ref.get(), "exists", False):
return False
now = datetime.now(timezone.utc)
update_data: Dict[str, Any] = {
'status': status,
'updated_at': now,
}
if status == WrappedStatus.DONE:
update_data['completed_at'] = now
update_data['result'] = result
update_data['error'] = None
elif status == WrappedStatus.ERROR:
update_data['error'] = error
update_data['result'] = None
wrapped_ref.update(update_data)
return True
def update_wrapped_progress(uid: str, year: int, progress: Dict[str, Any]) -> bool:
"""
Update the progress of a wrapped generation (heartbeat).
Args:
uid: User ID
year: Year (e.g., 2025)
progress: Progress info (e.g., {"step": "computing_stats", "pct": 0.5})
Returns:
True if updated successfully
"""
user_ref = db.collection('users').document(uid)
wrapped_ref = user_ref.collection(WRAPPED_COLLECTION).document(str(year))
if not getattr(wrapped_ref.get(), "exists", False):
return False
wrapped_ref.update(
{
'progress': progress,
'updated_at': datetime.now(timezone.utc),
}
)
return True
def reset_wrapped_for_regeneration(uid: str, year: int) -> Dict[str, Any]:
"""
Reset a stuck or errored wrapped document for regeneration.
Args:
uid: User ID
year: Year (e.g., 2025)
Returns:
The updated wrapped document data
"""
now = datetime.now(timezone.utc)
wrapped_data: Dict[str, Any] = {
'year': year,
'status': WrappedStatus.PROCESSING,
'started_at': now,
'updated_at': now,
'completed_at': None,
'result': None,
'error': None,
'progress': None,
'schema_version': 1,
}
user_ref = db.collection('users').document(uid)
wrapped_ref = user_ref.collection(WRAPPED_COLLECTION).document(str(year))
wrapped_ref.set(wrapped_data)
return wrapped_data
def is_wrapped_stuck(wrapped_data: Dict[str, Any], stale_minutes: int = 15) -> bool:
"""
Check if a wrapped generation is stuck (no heartbeat for stale_minutes).
Args:
wrapped_data: The wrapped document data
stale_minutes: Minutes after which a processing job is considered stuck
Returns:
True if the job appears stuck
"""
if wrapped_data.get('status') != WrappedStatus.PROCESSING:
return False
updated_at_raw = wrapped_data.get('updated_at')
if not updated_at_raw:
return True
updated_at = _coerce_timestamp(updated_at_raw)
if updated_at is None:
return True
now = datetime.now(timezone.utc)
elapsed = (now - updated_at).total_seconds() / 60
return elapsed > stale_minutes