-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdatabase.py
More file actions
180 lines (153 loc) · 6.2 KB
/
database.py
File metadata and controls
180 lines (153 loc) · 6.2 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
import logging
import shutil
from datetime import datetime
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from config import settings
log = logging.getLogger(__name__)
engine = create_engine(
settings.database_url,
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_pre_ping=True, # verify connections before use
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class Base(DeclarativeBase):
pass
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def init_db():
# Add new enum values BEFORE create_all (so the enum type exists with all values)
with engine.connect() as conn:
# Add new MeetingStatus enum values
for val in ("RECORDING", "FINALIZING"):
try:
conn.execute(text(
f"ALTER TYPE meetingstatus ADD VALUE IF NOT EXISTS '{val}'"
))
except Exception as e:
log.debug(f"Enum value meetingstatus.{val}: {e}")
# Add new JobType enum values
for val in ("POLISH_PASS", "FINALIZE_LIVE", "REDIARIZE", "REIDENTIFY", "EXTRACT_INSIGHTS"):
try:
conn.execute(text(
f"ALTER TYPE jobtype ADD VALUE IF NOT EXISTS '{val}'"
))
except Exception as e:
log.debug(f"Enum value jobtype.{val}: {e}")
conn.commit()
Base.metadata.create_all(bind=engine)
# Add new columns for live mode (safe to re-run)
migrations = [
"ALTER TABLE meetings ADD COLUMN IF NOT EXISTS mode VARCHAR DEFAULT 'upload'",
"ALTER TABLE meetings ADD COLUMN IF NOT EXISTS recording_status VARCHAR",
"ALTER TABLE meetings ADD COLUMN IF NOT EXISTS polish_history JSON",
"ALTER TABLE meetings ADD COLUMN IF NOT EXISTS is_encrypted BOOLEAN DEFAULT FALSE",
"ALTER TABLE meetings ADD COLUMN IF NOT EXISTS encryption_salt TEXT",
"ALTER TABLE meetings ADD COLUMN IF NOT EXISTS encryption_verify TEXT",
"ALTER TABLE action_results ADD COLUMN IF NOT EXISTS is_encrypted BOOLEAN DEFAULT FALSE",
"ALTER TABLE meetings ADD COLUMN IF NOT EXISTS vocabulary TEXT",
# Full-text search index on segment text
"CREATE INDEX IF NOT EXISTS ix_segments_text_search ON segments USING gin (to_tsvector('simple', text))",
]
with engine.connect() as conn:
for sql in migrations:
try:
conn.execute(text(sql))
except Exception as e:
log.debug(f"Migration skipped: {sql[:60]}... ({e})")
conn.commit()
def recover_stale_jobs():
"""Mark any jobs stuck in RUNNING/PENDING as FAILED on startup.
If the server restarts while a Celery task was running, the job
status is stuck. This cleans them up so the user can retry.
"""
from models.job import Job, JobStatus
from models import Meeting, MeetingStatus
db = SessionLocal()
try:
stale_jobs = db.query(Job).filter(
Job.status.in_([JobStatus.RUNNING, JobStatus.PENDING])
).all()
for job in stale_jobs:
job.status = JobStatus.FAILED
job.error = "Task interrupted by server restart. Please retry."
job.completed_at = datetime.utcnow()
# Also reset the meeting status if it was stuck in PROCESSING/FINALIZING
meeting = db.query(Meeting).filter(Meeting.id == job.meeting_id).first()
if meeting and meeting.status in (MeetingStatus.PROCESSING, MeetingStatus.FINALIZING):
meeting.status = MeetingStatus.FAILED
if stale_jobs:
db.commit()
log.info(f"Recovered {len(stale_jobs)} stale job(s)")
finally:
db.close()
def cleanup_orphaned_storage():
"""Remove storage directories for meetings that no longer exist in the DB."""
from config import get_storage_path
from models import Meeting
storage = get_storage_path()
if not storage.exists():
return
db = SessionLocal()
try:
meeting_ids = {row[0] for row in db.query(Meeting.id).all()}
removed = 0
for d in storage.iterdir():
if d.is_dir() and d.name not in meeting_ids:
shutil.rmtree(d, ignore_errors=True)
removed += 1
if removed:
log.info(f"Cleaned up {removed} orphaned storage directory(s)")
finally:
db.close()
def seed_default_actions():
"""Create default actions if none exist."""
from models.action import Action
db = SessionLocal()
try:
if db.query(Action).count() > 0:
return
defaults = [
Action(
name="Sammanfattning",
prompt=(
"Du ar en motesassistent. Skriv en tydlig och koncis sammanfattning av motet. "
"Inkludera: huvudamnen som diskuterades, viktiga beslut som fattades, "
"och eventuella olosta fragor. Skriv pa svenska."
),
is_default=True,
),
Action(
name="Atgardslista",
prompt=(
"Du ar en motesassistent. Skapa en strukturerad atgardslista fran motet. "
"For varje atgard, ange:\n"
"- Vad som ska goras\n"
"- Vem som ar ansvarig (om det framgar)\n"
"- Deadline (om det namns)\n\n"
"Formatera som en numrerad lista. Skriv pa svenska."
),
is_default=True,
),
Action(
name="Avidentifierad version",
prompt=(
"Du ar en integritetsspecialist. Skriv om transkriberingen sa att alla "
"personnamn ersatts med 'Person A', 'Person B', 'Person C' osv. "
"Ersatt aven organisationsnamn, platser och andra identifierande detaljer "
"med generiska termer. Behall innehallet intakt. Skriv pa svenska."
),
is_default=True,
),
]
for action in defaults:
db.add(action)
db.commit()
finally:
db.close()