-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
416 lines (329 loc) Β· 13.6 KB
/
main.py
File metadata and controls
416 lines (329 loc) Β· 13.6 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
#!/usr/bin/env python3
"""
Gradio App - A simple Gradio application skeleton.
"""
import argparse
import atexit
import logging
import os
import signal
from dotenv import load_dotenv
from src.ui.interface import THEMES, create_interface
logger = logging.getLogger(__name__)
# Global flag to prevent multiple signal handlers
_shutdown_in_progress = False
def handle_migration_commands(args) -> int:
"""Handle database migration commands.
Args:
args: Parsed command line arguments
Returns:
Exit code (0 for success, 1 for error)
"""
try:
from src.utils.database import get_migration_status, run_database_migrations
if args.migration_status:
logger.info("π Checking database migration status...")
status = get_migration_status()
print("\n" + "=" * 50)
print("π DATABASE MIGRATION STATUS")
print("=" * 50)
print(f"π Migrations directory: {status['migrations_directory']}")
print(f"π Total migrations: {status['total_migrations']}")
print(f"β
Applied: {status['applied_count']}")
print(f"β³ Pending: {status['pending_count']}")
if status['migrations']['pending']:
print(f"\nβ³ Pending migrations:")
for migration in status['migrations']['pending']:
print(f" β’ {migration}")
if status['migrations']['applied']:
print(f"\nβ
Applied migrations:")
for migration in status['migrations']['applied']:
print(f" β’ {migration}")
print("=" * 50)
return 0
elif args.migration_dry_run:
logger.info("π§ͺ Running migration dry run...")
successful, failed = run_database_migrations(dry_run=True)
print("\n" + "=" * 50)
print("π§ͺ MIGRATION DRY RUN RESULTS")
print("=" * 50)
if successful:
print(f"β
Would apply {len(successful)} migrations:")
for migration in successful:
print(f" β’ {migration}")
else:
print("βΉοΈ No migrations to apply")
if failed:
print(f"\nβ Would fail {len(failed)} migrations:")
for migration in failed:
print(f" β’ {migration}")
print("=" * 50)
return 0
elif args.migrate:
logger.info("π Running database migrations...")
successful, failed = run_database_migrations(dry_run=False)
print("\n" + "=" * 50)
print("π MIGRATION EXECUTION RESULTS")
print("=" * 50)
if successful:
print(f"β
Successfully applied {len(successful)} migrations:")
for migration in successful:
print(f" β’ {migration}")
if failed:
print(f"\nβ Failed {len(failed)} migrations:")
for migration in failed:
print(f" β’ {migration}")
print("=" * 50)
return 1
if not successful and not failed:
print("βΉοΈ No migrations to apply")
print("=" * 50)
return 0
elif args.schema_validate:
logger.info("π Validating database schema...")
from src.utils.database import get_migration_runner
runner = get_migration_runner()
# Validate ymemo table
ymemo_expected = [
"id",
"name",
"duration",
"transcription",
"created_at",
"audio_file_path",
]
ymemo_validation = runner.validate_expected_schema("ymemo", ymemo_expected)
# Validate ymemo_persona table if it exists
persona_expected = ["id", "name", "description", "created_at", "updated_at"]
persona_validation = runner.validate_expected_schema(
"ymemo_persona", persona_expected
)
print("\n" + "=" * 50)
print("π SCHEMA VALIDATION RESULTS")
print("=" * 50)
print(f"π ymemo table:")
print(f" β
Valid: {ymemo_validation['valid']}")
if ymemo_validation.get('missing_columns'):
print(f" β Missing columns: {ymemo_validation['missing_columns']}")
if ymemo_validation.get('extra_columns'):
print(f" β οΈ Extra columns: {ymemo_validation['extra_columns']}")
print(f"\nπ ymemo_persona table:")
if persona_validation.get('table_exists'):
print(f" β
Valid: {persona_validation['valid']}")
if persona_validation.get('missing_columns'):
print(
f" β Missing columns: {persona_validation['missing_columns']}"
)
if persona_validation.get('extra_columns'):
print(f" β οΈ Extra columns: {persona_validation['extra_columns']}")
else:
print(
" βΉοΈ Table does not exist (expected for pre-persona deployments)"
)
overall_valid = ymemo_validation['valid'] and (
not persona_validation.get('table_exists')
or persona_validation['valid']
)
print(
f"\nπ― Overall schema validity: {'β
VALID' if overall_valid else 'β ISSUES FOUND'}"
)
print("=" * 50)
return 0 if overall_valid else 1
elif args.database_state:
logger.info("π Analyzing database state...")
from src.utils.database import get_migration_runner
runner = get_migration_runner()
db_state = runner.detect_database_state()
print("\n" + "=" * 50)
print("π DATABASE STATE ANALYSIS")
print("=" * 50)
if db_state.get("error"):
print(f"β Error detecting state: {db_state['error']}")
print("=" * 50)
return 1
print(
f"π Database Type: {'π± Fresh' if db_state['is_fresh_database'] else 'ποΈ Existing'}"
)
print(
f"π ymemo table: {'β
Exists' if db_state['ymemo_table_exists'] else 'β Missing'}"
)
print(
f"π€ ymemo_persona table: {'β
Exists' if db_state['ymemo_persona_table_exists'] else 'β Missing'}"
)
print(
f"ποΈ Migration tracking: {'β
Exists' if db_state['migration_table_exists'] else 'β Missing'}"
)
if db_state['is_partial_deployment']:
print(f"\nβ οΈ PARTIAL DEPLOYMENT DETECTED")
print(" This database is in an inconsistent state.")
if db_state['detected_issues']:
print(f"\nβ DETECTED ISSUES:")
for issue in db_state['detected_issues']:
print(f" β’ {issue}")
if db_state.get('ymemo_schema'):
print(f"\nπ ymemo table schema:")
print(f" Columns: {db_state['ymemo_schema']['column_count']}")
if db_state.get('ymemo_persona_schema'):
print(f"\nπ€ ymemo_persona table schema:")
print(f" Columns: {db_state['ymemo_persona_schema']['column_count']}")
print("=" * 50)
return 0
except Exception as e:
logger.error(f"β Migration command failed: {e}", exc_info=True)
print(f"\nβ Error: {e}")
return 1
def cleanup_on_exit():
"""Clean up resources on exit."""
logger.info("π§Ή Cleaning up resources on exit...")
try:
from src.managers.session_manager import get_audio_session
session = get_audio_session()
if session.is_recording():
logger.info("π Stopping recording on exit...")
# Use threading with timeout to prevent cleanup from hanging
import threading
stop_result = [False] # Use list to make it mutable
def stop_recording_thread():
try:
success = session.stop_recording()
stop_result[0] = success
logger.info(f"π Recording stopped: {success}")
except Exception as e:
logger.error(f"β Error stopping recording: {e}")
# Start stop operation in a separate thread
stop_thread = threading.Thread(target=stop_recording_thread)
stop_thread.daemon = True
stop_thread.start()
# Wait for up to 1 second for cleanup to complete
stop_thread.join(timeout=1.0)
if stop_thread.is_alive():
logger.warning("β οΈ Recording stop timed out - abandoning cleanup")
else:
logger.info(f"β
Recording cleanup completed: {stop_result[0]}")
logger.info("β
Cleanup completed")
except Exception as e:
logger.error(f"β Error during cleanup: {e}")
def signal_handler(signum, frame):
"""Handle signals like SIGINT, SIGTERM."""
global _shutdown_in_progress
if _shutdown_in_progress:
logger.info("π Shutdown already in progress, forcing exit...")
import os
os._exit(1)
_shutdown_in_progress = True
logger.info(f"π Received signal {signum}, shutting down gracefully...")
try:
cleanup_on_exit()
except Exception as e:
logger.error(f"β Error during signal cleanup: {e}")
finally:
logger.info("π Exiting application...")
# Use os._exit to force immediate termination
import os
os._exit(0)
def main():
"""Main entry point for the Gradio application."""
load_dotenv()
# Get log level from environment variable
log_level = os.getenv('LOG_LEVEL', 'INFO').upper()
# Configure logging
logging.basicConfig(
level=getattr(logging, log_level, logging.INFO),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
],
)
# Set specific logger levels based on environment
audio_log_level = getattr(logging, log_level, logging.INFO)
logging.getLogger('src.audio').setLevel(audio_log_level)
logging.getLogger('src.audio.providers.aws_transcribe').setLevel(audio_log_level)
logging.getLogger('src.audio.providers.pyaudio_capture').setLevel(audio_log_level)
logging.getLogger('src.core.processor').setLevel(audio_log_level)
logging.getLogger('src.managers.session_manager').setLevel(audio_log_level)
logging.getLogger('src.managers.meeting_repository').setLevel(audio_log_level)
parser = argparse.ArgumentParser(
description="Gradio App - Simple Gradio application",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--ip",
type=str,
default="127.0.0.1",
help="IP address to bind to (default: 127.0.0.1)",
)
parser.add_argument(
"--port", type=int, default=7860, help="Port to listen on (default: 7860)"
)
parser.add_argument(
"--theme",
type=str,
default="Ocean",
choices=list(THEMES.keys()),
help=f"UI theme to use (default: Ocean). Available: {', '.join(THEMES.keys())}",
)
parser.add_argument(
"--share", action="store_true", help="Create a public shareable link"
)
# Database migration commands
parser.add_argument(
"--migrate", action="store_true", help="Run pending database migrations"
)
parser.add_argument(
"--migration-status", action="store_true", help="Show database migration status"
)
parser.add_argument(
"--migration-dry-run",
action="store_true",
help="Show what migrations would be applied (dry run)",
)
parser.add_argument(
"--schema-validate",
action="store_true",
help="Validate current database schema against expected structure",
)
parser.add_argument(
"--database-state",
action="store_true",
help="Show detailed database state information",
)
args = parser.parse_args()
# Handle migration commands first (before starting the app)
if (
args.migration_status
or args.migration_dry_run
or args.migrate
or args.schema_validate
or args.database_state
):
return handle_migration_commands(args)
logger.info("π Starting Gradio App...")
logger.info(f"π Server: http://{args.ip}:{args.port}")
logger.info(f"π¨ Theme: {args.theme}")
logger.info(f"π€ Audio logging: {log_level}")
# Register cleanup handlers
atexit.register(cleanup_on_exit)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Create and launch the interface
demo = create_interface(theme_name=args.theme)
try:
demo.queue(
max_size=20, # Maximum number of requests in queue
api_open=False, # Don't expose API endpoints
).launch(
server_name=args.ip,
server_port=args.port,
share=args.share,
show_error=True,
)
except KeyboardInterrupt:
logger.info("\nπ Shutting down Gradio App...")
cleanup_on_exit()
except Exception as e:
logger.error(f"β Error starting server: {e}", exc_info=True)
cleanup_on_exit()
return 1
return 0
if __name__ == "__main__":
exit(main())