Roudrigus commited on
Commit
3168916
·
verified ·
1 Parent(s): 91666a7

Upload 17 files

Browse files
Files changed (17) hide show
  1. __init__.py +0 -0
  2. admin.py +1608 -0
  3. aluno.py +581 -0
  4. app.py +69 -0
  5. app_config.py +25 -0
  6. backup_hf.py +126 -0
  7. comments.py +56 -0
  8. db.py +44 -0
  9. db_ready.py +44 -0
  10. gallery.py +195 -0
  11. gallery_storage.py +127 -0
  12. models.py +130 -0
  13. presence.py +60 -0
  14. requirements.txt +20 -0
  15. student_auth.py +71 -0
  16. utils.py +76 -0
  17. video_access.py +87 -0
__init__.py ADDED
File without changes
admin.py ADDED
@@ -0,0 +1,1608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # admin.py
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ import io
5
+ import re
6
+ import json
7
+ import sqlite3
8
+ import zipfile
9
+ import traceback
10
+ import time as _time
11
+ from datetime import datetime, date, time, timedelta
12
+ from typing import Optional, Dict, Any, List, Tuple
13
+
14
+ import pandas as pd
15
+ import streamlit as st
16
+ from sqlalchemy import func
17
+
18
+ # ==========================
19
+ # Imports de modelos
20
+ # ==========================
21
+ from models import (
22
+ Course, Lesson, Material, Schedule, Enrollment, Grade, MakeupRequest, Certificate
23
+ )
24
+
25
+ # ==========================
26
+ # Imports com fallback (modular → raiz)
27
+ # ==========================
28
+ try:
29
+ from core.db_ready import ensure_db_ready, commit_with_retry
30
+ except Exception:
31
+ from db_ready import ensure_db_ready, commit_with_retry
32
+
33
+ try:
34
+ from core.student_auth import set_student_password
35
+ except Exception:
36
+ from student_auth import set_student_password
37
+
38
+ try:
39
+ from core.video_access import (
40
+ get_video_visibility, set_video_visibility,
41
+ get_video_acl_emails, set_video_acl_emails,
42
+ is_video_allowed_for_student,
43
+ _ensure_video_access_tables as ensure_video_access_tables,
44
+ )
45
+ except Exception:
46
+ from video_access import (
47
+ get_video_visibility, set_video_visibility,
48
+ get_video_acl_emails, set_video_acl_emails,
49
+ is_video_allowed_for_student,
50
+ )
51
+ # Fallback simples se a função ensure não existir na raiz
52
+ def ensure_video_access_tables():
53
+ pass
54
+
55
+ try:
56
+ from core.presence import (
57
+ get_online_users, PRESENCE_ONLINE_THRESHOLD_SEC,
58
+ _ensure_presence_table as ensure_presence_table,
59
+ )
60
+ except Exception:
61
+ from presence import get_online_users, PRESENCE_ONLINE_THRESHOLD_SEC
62
+ def ensure_presence_table():
63
+ pass
64
+
65
+ try:
66
+ from core.comments import (
67
+ get_comments, add_comment, delete_comment,
68
+ _ensure_comments_table as ensure_comments_table,
69
+ )
70
+ except Exception:
71
+ from comments import get_comments, add_comment, delete_comment
72
+ def ensure_comments_table():
73
+ pass
74
+
75
+ try:
76
+ from core.backup_hf import (
77
+ HF_HUB_AVAILABLE, sync_to_hf_dataset,
78
+ auto_backup_tick as _auto_backup_tick,
79
+ _sanitize_repo_id,
80
+ )
81
+ except Exception:
82
+ from backup_hf import (
83
+ HF_HUB_AVAILABLE, sync_to_hf_dataset,
84
+ auto_backup_tick as _auto_backup_tick,
85
+ _sanitize_repo_id,
86
+ )
87
+
88
+ try:
89
+ from ui.gallery import aba_galeria_relatorios
90
+ except Exception:
91
+ from gallery import aba_galeria_relatorios
92
+
93
+ # Settings (suporta pasta 'Config' e 'config')
94
+ try:
95
+ from Config.settings import ADMIN_FIXED_PASS_HASH, AUTO_BKP_INTERVAL_SEC
96
+ except Exception:
97
+ try:
98
+ from config.settings import ADMIN_FIXED_PASS_HASH, AUTO_BKP_INTERVAL_SEC
99
+ except Exception:
100
+ # Fallbacks
101
+ import hashlib as _hashlib
102
+ ADMIN_FIXED_PASS_HASH = _hashlib.sha256("21003887".encode()).hexdigest()
103
+ AUTO_BKP_INTERVAL_SEC = 600
104
+
105
+ # Utilitários
106
+ try:
107
+ from utils import save_uploaded_file, human_dt, generate_certificate_pdf, ADMIN_USER
108
+ except Exception:
109
+ # Fallbacks simples se algo não existir
110
+ ADMIN_USER = "admin"
111
+ def save_uploaded_file(file, base_dir="data"):
112
+ out_dir = os.path.join(base_dir)
113
+ os.makedirs(out_dir, exist_ok=True)
114
+ path = os.path.join(out_dir, file.name)
115
+ with open(path, "wb") as f:
116
+ f.write(file.getbuffer())
117
+ return path
118
+ def human_dt(dt_obj):
119
+ try:
120
+ return pd.to_datetime(dt_obj).strftime("%d/%m/%Y %H:%M")
121
+ except Exception:
122
+ return str(dt_obj)
123
+ def generate_certificate_pdf(course_title: str, student_name: str, output_dir: str) -> str:
124
+ os.makedirs(output_dir, exist_ok=True)
125
+ # Gera um PDF simples de placeholder
126
+ path = os.path.join(output_dir, f"cert_{student_name.replace(' ', '_')}.pdf")
127
+ with open(path, "wb") as f:
128
+ f.write(b"%PDF-1.4\n% placeholder certificate\n")
129
+ return path
130
+
131
+ # Path do banco
132
+ try:
133
+ from db import DB_PATH
134
+ except Exception:
135
+ DB_PATH = os.path.join("data", "db.sqlite")
136
+
137
+
138
+ # ==========================
139
+ # Helpers locais (texto, YouTube, tópico da agenda)
140
+ # ==========================
141
+ def is_url(s: Optional[str]) -> bool:
142
+ s = (s or "").strip().lower()
143
+ return s.startswith("http://") or s.startswith("https://")
144
+
145
+
146
+ def normalize_youtube_url(url: str) -> str:
147
+ if not url:
148
+ return url
149
+ u = url.strip()
150
+
151
+ m = re.search(r"(?:https?://)?(?:www\.)?youtu\.be/([A-Za-z0-9_-]{6,})", u)
152
+ if m:
153
+ vid = m.group(1)
154
+ return f"https://www.youtube.com/watch?v={vid}"
155
+
156
+ m = re.search(r"(?:https?://)?(?:www\.)?youtube\.com/watch\?v=([A-Za-z0-9_-]{6,})", u)
157
+ if m:
158
+ return f"https://www.youtube.com/watch?v={m.group(1)}"
159
+
160
+ m = re.search(r"(?:https?://)?(?:www\.)?youtube\.com/embed/([A-Za-z0-9_-]{6,})", u)
161
+ if m:
162
+ return f"https://www.youtube.com/watch?v={m.group(1)}"
163
+
164
+ m = re.search(r"(?:https?://)?(?:www\.)?youtube\.com/shorts/([A-Za-z0-9_-]{6,})", u)
165
+ if m:
166
+ return f"https://www.youtube.com/watch?v={m.group(1)}"
167
+
168
+ return u
169
+
170
+
171
+ def parse_schedule_topic(topic_raw: str) -> Dict[str, Any]:
172
+ defaults = {
173
+ "topic": None,
174
+ "module_id": None,
175
+ "assigned_emails": [],
176
+ "occupancy": "",
177
+ "module_index": None,
178
+ "details": None,
179
+ "descricao": None,
180
+ "semana": None,
181
+ "off_schedule": False,
182
+ "aluno_nome": None,
183
+ "matricula": None,
184
+ }
185
+ if not topic_raw:
186
+ return defaults
187
+ s = (topic_raw or "").strip()
188
+
189
+ # 1) JSON
190
+ try:
191
+ obj = json.loads(s)
192
+ if isinstance(obj, dict):
193
+ out = defaults.copy()
194
+ out["topic"] = obj.get("topic") or obj.get("titulo") or obj.get("assunto") or None
195
+ out["module_id"] = obj.get("module_id") or obj.get("mod_id") or obj.get("lesson_id") or None
196
+ emails = obj.get("assigned_emails") or obj.get("emails") or []
197
+ if isinstance(emails, str):
198
+ emails = [e.strip().lower() for e in emails.split(",") if e.strip()]
199
+ elif isinstance(emails, list):
200
+ emails = [(e or "").strip().lower() for e in emails if (e or "").strip()]
201
+ else:
202
+ emails = []
203
+ out["assigned_emails"] = emails
204
+ out["occupancy"] = (obj.get("occupancy") or obj.get("ocupacao") or "").strip()
205
+ out["module_index"] = obj.get("module_index") or obj.get("indice") or None
206
+ out["details"] = obj.get("details")
207
+ out["descricao"] = obj.get("descricao")
208
+ out["semana"] = obj.get("semana")
209
+ out["off_schedule"] = bool(obj.get("off_schedule", False))
210
+ out["aluno_nome"] = obj.get("aluno_nome")
211
+ out["matricula"] = obj.get("matricula")
212
+ return out
213
+ except Exception:
214
+ pass
215
+
216
+ # 2) "k: v; k: v"
217
+ try:
218
+ parts = [p.strip() for p in re.split(r"[;|]\s*", s) if p.strip()]
219
+ kv = {}
220
+ for p in parts:
221
+ if ":" in p:
222
+ k, v = p.split(":", 1)
223
+ kv[k.strip().lower()] = v.strip()
224
+ if kv:
225
+ out = defaults.copy()
226
+ out["topic"] = kv.get("topic") or kv.get("assunto") or None
227
+ mid = kv.get("module_id")
228
+ out["module_id"] = int(mid) if (mid and str(mid).isdigit()) else None
229
+ emails = kv.get("assigned_emails") or kv.get("emails") or ""
230
+ out["assigned_emails"] = [e.strip().lower() for e in emails.split(",") if e.strip()]
231
+ out["occupancy"] = kv.get("occupancy") or kv.get("ocupacao") or ""
232
+ out["module_index"] = kv.get("module_index") or kv.get("indice") or None
233
+ out["details"] = kv.get("details") or kv.get("descricao")
234
+ out["descricao"] = kv.get("descricao")
235
+ out["semana"] = kv.get("semana")
236
+ out["off_schedule"] = str(kv.get("off_schedule", "")).strip().lower() in ("1","true","sim","yes")
237
+ out["aluno_nome"] = kv.get("aluno_nome")
238
+ out["matricula"] = kv.get("matricula")
239
+ return out
240
+ except Exception:
241
+ pass
242
+
243
+ out = defaults.copy()
244
+ out["topic"] = s
245
+ return out
246
+
247
+
248
+ def _fmt_duration(sec: int) -> str:
249
+ if sec is None:
250
+ return "—"
251
+ sec = int(max(0, sec))
252
+ m, s = divmod(sec, 60)
253
+ h, m = divmod(m, 60)
254
+ d, h = divmod(h, 24)
255
+ parts = []
256
+ if d: parts.append(f"{d}d")
257
+ if h: parts.append(f"{h}h")
258
+ if m: parts.append(f"{m}m")
259
+ parts.append(f"{s}s")
260
+ return " ".join(parts)
261
+
262
+
263
+ # ==========================================================
264
+ # Helpers de agenda (importação/limpeza) — mesmos do seu projeto
265
+ # ==========================================================
266
+ def _strip_accents_ag(s: str) -> str:
267
+ import unicodedata
268
+ if s is None:
269
+ return s
270
+ return ''.join(ch for ch in unicodedata.normalize('NFKD', str(s)) if not unicodedata.combining(ch))
271
+
272
+ def _norm_col_ag(col: str) -> str:
273
+ col = _strip_accents_ag(col).lower()
274
+ col = re.sub(r'\W+', '_', col)
275
+ return col.strip('_')
276
+
277
+ def _normalize_semana_label(s: str) -> str:
278
+ if not s:
279
+ return s
280
+ s = s.strip()
281
+ s = re.sub(r'^semama', 'Semana', s, flags=re.I) # corrige "Semama9"
282
+ m = re.match(r'^(semana)\s*([0-9]+)$', s, flags=re.I)
283
+ if m:
284
+ s = f"Semana{m.group(2)}"
285
+ return s
286
+
287
+ def _split_horario_range(horario_str: str) -> Tuple[Optional[str], Optional[str]]:
288
+ if not horario_str:
289
+ return None, None
290
+ s = str(horario_str).strip()
291
+ s = re.sub(r'[–—−]+', '-', s) # normaliza qualquer traço para '-'
292
+ parts = re.split(r'\s*-\s*', s)
293
+ if len(parts) == 2:
294
+ return parts[0], parts[1]
295
+ return None, None
296
+
297
+ def _parse_tsv_text(text: str) -> pd.DataFrame:
298
+ buf = io.StringIO(text.strip())
299
+ df = pd.read_csv(
300
+ buf,
301
+ sep='\t',
302
+ engine='python',
303
+ quoting=0, # csv.QUOTE_MINIMAL
304
+ quotechar='"',
305
+ keep_default_na=False
306
+ )
307
+ return df
308
+
309
+ def _read_agenda_uploaded(file) -> Optional[pd.DataFrame]:
310
+ name = (file.name or "").lower()
311
+ try:
312
+ if name.endswith(('.xlsx', '.xls')):
313
+ return pd.read_excel(file, engine='openpyxl')
314
+ elif name.endswith(('.csv', '.tsv', '.txt')):
315
+ content = file.read().decode('utf-8-sig', errors='ignore')
316
+ try:
317
+ return _parse_tsv_text(content)
318
+ except Exception:
319
+ return pd.read_csv(io.StringIO(content), sep=',', engine='python', quoting=0, quotechar='"', keep_default_na=False)
320
+ else:
321
+ st.error("Formato não suportado. Use CSV/TSV/TXT/Excel.")
322
+ return None
323
+ except Exception as e:
324
+ st.error(f"Falha ao ler arquivo: {e}")
325
+ return None
326
+
327
+ def parse_time_hhmm(s: str) -> Optional[time]:
328
+ try:
329
+ hh, mm = s.split(":")
330
+ return time(int(hh), int(mm))
331
+ except Exception:
332
+ return None
333
+
334
+ def parse_time_range(rng: str) -> Tuple[Optional[time], Optional[time]]:
335
+ if not rng:
336
+ return None, None
337
+ s = (rng or "").replace("–", "-").replace("—", "-").replace("−", "-")
338
+ parts = [p.strip() for p in s.split("-") if p.strip()]
339
+ if len(parts) != 2:
340
+ return None, None
341
+ return parse_time_hhmm(parts[0]), parse_time_hhmm(parts[1])
342
+
343
+ def _norm(s: str) -> str:
344
+ s = (s or "").strip().lower()
345
+ s = (s.replace("á","a").replace("à","a").replace("ã","a").replace("â","a")
346
+ .replace("é","e").replace("ê","e")
347
+ .replace("í","i")
348
+ .replace("ó","o").replace("ô","o").replace("õ","o")
349
+ .replace("ú","u").replace("ç","c"))
350
+ return s
351
+
352
+ def _clean_agenda_df(df_raw: pd.DataFrame) -> pd.DataFrame:
353
+ if df_raw is None or df_raw.empty:
354
+ return pd.DataFrame()
355
+
356
+ df = df_raw.copy()
357
+ df.columns = [_norm_col_ag(c) for c in df.columns]
358
+
359
+ aliases = {
360
+ 'semana': 'semana',
361
+ 'data': 'data',
362
+ 'dia': 'dia',
363
+ 'horario': 'horario',
364
+ 'ocupacao': 'ocupacao',
365
+ 'aluno': 'aluno',
366
+ 'mat': 'matricula',
367
+ 'mat_': 'matricula',
368
+ 'descricao': 'descricao',
369
+ 'tema': 'tema'
370
+ }
371
+ rename = {}
372
+ for c in df.columns:
373
+ if c in aliases:
374
+ rename[c] = aliases[c]
375
+ elif c.startswith('mat'):
376
+ rename[c] = 'matricula'
377
+ else:
378
+ rename[c] = c
379
+ df = df.rename(columns=rename)
380
+
381
+ required = ['semana','data','dia','horario','ocupacao','aluno','matricula','descricao','tema']
382
+ for col in required:
383
+ if col not in df.columns:
384
+ df[col] = ""
385
+
386
+ for c in df.columns:
387
+ if df[c].dtype == object:
388
+ df[c] = df[c].astype(str).str.strip()
389
+
390
+ df['semana'] = df['semana'].apply(_normalize_semana_label)
391
+ df['data'] = pd.to_datetime(df['data'], dayfirst=True, errors='coerce')
392
+
393
+ ini_fim = df['horario'].apply(_split_horario_range)
394
+ df['inicio_hhmm'] = [t[0] if t else None for t in ini_fim]
395
+ df['fim_hhmm'] = [t[1] if t else None for t in ini_fim]
396
+
397
+ df['fora_do_cronograma'] = df['tema'].str.contains(r'\(fora do cronograma\)', case=False, na=False)
398
+ df['tema'] = df['tema'].str.replace(r'\s*\(fora do cronograma\)\s*', '', regex=True).str.strip()
399
+ df['vago'] = df['aluno'].str.strip().str.upper().eq('VAGO')
400
+
401
+ try:
402
+ df['matricula'] = pd.to_numeric(df['matricula'], errors='ignore')
403
+ except Exception:
404
+ pass
405
+
406
+ df = df.drop_duplicates(subset=['semana','data','dia','horario','aluno','tema','matricula']).reset_index(drop=True)
407
+ return df
408
+
409
+
410
+ # ==========================================================
411
+ # FullCalendar helpers
412
+ # ==========================================================
413
+ from streamlit_calendar import calendar as st_calendar
414
+ from plotly import colors as pcolors
415
+
416
+ def _to_json_safe(obj):
417
+ if obj is None:
418
+ return None
419
+ if isinstance(obj, (str, int, float, bool)):
420
+ return obj
421
+ if isinstance(obj, datetime):
422
+ return obj.replace(microsecond=0).isoformat()
423
+ if isinstance(obj, date):
424
+ return obj.isoformat()
425
+ if isinstance(obj, time):
426
+ return obj.strftime("%H:%M:%S")
427
+ if isinstance(obj, dict):
428
+ return {str(k): _to_json_safe(v) for k, v in obj.items()}
429
+ if isinstance(obj, (list, tuple, set)):
430
+ return [_to_json_safe(v) for v in obj]
431
+ return str(obj)
432
+
433
+ def json_sanitize_events(events: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
434
+ safe = []
435
+ for ev in events:
436
+ ev_copy = _to_json_safe(json.loads(json.dumps(ev, ensure_ascii=False)))
437
+ safe.append(ev_copy)
438
+ return safe
439
+
440
+ def _make_color_map(emails: List[str]) -> Dict[str, str]:
441
+ palette = (
442
+ pcolors.qualitative.Plotly
443
+ + pcolors.qualitative.D3
444
+ + pcolors.qualitative.Set3
445
+ + pcolors.qualitative.Pastel
446
+ + pcolors.qualitative.Vivid
447
+ )
448
+ cmap = {}
449
+ idx = 0
450
+ for e in sorted(set(emails)):
451
+ if e in ("Sem aluno",):
452
+ cmap[e] = "#7f8c8d"
453
+ else:
454
+ cmap[e] = palette[idx % len(palette)]
455
+ idx += 1
456
+ return cmap
457
+
458
+ def build_fullcalendar_events(agenda_list: List[Schedule], mods_by_id: Dict[int, Lesson]):
459
+ rows = []
460
+ who = set()
461
+
462
+ for a in agenda_list:
463
+ meta = parse_schedule_topic(a.topic)
464
+ mod = mods_by_id.get(meta.get("module_id")) if meta.get("module_id") else None
465
+ title = mod.title if mod else (meta.get("topic") or "—")
466
+ desc = meta.get("details") or meta.get("descricao") or (meta.get("topic") or "")
467
+ occupancy = meta.get("occupancy") or ""
468
+ module_index = meta.get("module_index") or ""
469
+
470
+ if not a.class_date:
471
+ continue
472
+ start_dt = datetime.combine(a.class_date, a.start_time or time(0, 0))
473
+ end_dt = datetime.combine(a.class_date, a.end_time or (a.start_time or time(0, 0)))
474
+ if end_dt <= start_dt:
475
+ end_dt = start_dt + timedelta(minutes=60)
476
+
477
+ emails = meta.get("assigned_emails") or []
478
+ if emails:
479
+ for em in emails:
480
+ who.add(em)
481
+ rows.append({
482
+ "title": title,
483
+ "start": start_dt.isoformat(),
484
+ "end": end_dt.isoformat(),
485
+ "who": em,
486
+ "extendedProps": {
487
+ "aluno": em,
488
+ "ocupacao": occupancy,
489
+ "mod_index": module_index,
490
+ "descricao": desc,
491
+ "data": a.class_date.strftime("%d/%m/%Y"),
492
+ "inicio": a.start_time.strftime("%H:%M") if a.start_time else "",
493
+ "fim": a.end_time.strftime("%H:%M") if a.end_time else "",
494
+ },
495
+ })
496
+ else:
497
+ who.add("Sem aluno")
498
+ rows.append({
499
+ "title": title,
500
+ "start": start_dt.isoformat(),
501
+ "end": end_dt.isoformat(),
502
+ "who": "Sem aluno",
503
+ "extendedProps": {
504
+ "aluno": "Sem aluno",
505
+ "ocupacao": occupancy,
506
+ "mod_index": module_index,
507
+ "descricao": desc,
508
+ "data": a.class_date.strftime("%d/%m/%Y"),
509
+ "inicio": a.start_time.strftime("%H:%M") if a.start_time else "",
510
+ "fim": a.end_time.strftime("%H:%M") if a.end_time else "",
511
+ },
512
+ })
513
+
514
+ color_map = _make_color_map(list(who))
515
+ for ev in rows:
516
+ ev["color"] = color_map.get(ev.get("who"), "#7f8c8d")
517
+ return rows, color_map
518
+
519
+ def render_calendar(events, options=None, custom_css=None, key=None):
520
+ try:
521
+ import inspect
522
+ sig = inspect.signature(st_calendar)
523
+ except Exception:
524
+ return st_calendar(events=events, options=options, key=key)
525
+
526
+ kwargs = {"events": events}
527
+ if "options" in sig.parameters:
528
+ kwargs["options"] = options
529
+ if "custom_css" in sig.parameters and custom_css:
530
+ kwargs["custom_css"] = custom_css
531
+ if "key" in sig.parameters and key:
532
+ kwargs["key"] = key
533
+ return st_calendar(**kwargs)
534
+
535
+
536
+ # ==========================================================
537
+ # Utilidades: reset e normalização
538
+ # ==========================================================
539
+ def reset_database(db) -> Tuple[bool, Optional[str]]:
540
+ try:
541
+ db.query(Certificate).delete(synchronize_session=False)
542
+ db.query(Grade).delete(synchronize_session=False)
543
+ db.query(MakeupRequest).delete(synchronize_session=False)
544
+ db.query(Enrollment).delete(synchronize_session=False)
545
+ db.query(Schedule).delete(synchronize_session=False)
546
+ db.query(Material).delete(synchronize_session=False)
547
+ db.query(Lesson).delete(synchronize_session=False)
548
+ db.query(Course).delete(synchronize_session=False)
549
+ commit_with_retry(db)
550
+
551
+ # Auxiliares SQLite
552
+ ensure_comments_table()
553
+ ensure_presence_table()
554
+ ensure_video_access_tables()
555
+ with sqlite3.connect(DB_PATH) as conn:
556
+ c = conn.cursor()
557
+ c.execute("DELETE FROM student_auth")
558
+ c.execute("DELETE FROM video_access_list")
559
+ c.execute("DELETE FROM video_access")
560
+ c.execute("DELETE FROM presence")
561
+ c.execute("DELETE FROM comments")
562
+ conn.commit()
563
+ return True, None
564
+ except Exception as e:
565
+ db.rollback()
566
+ return False, str(e)
567
+
568
+ def normalize_and_dedup_enrollments(db) -> Tuple[int, int]:
569
+ ens = db.query(Enrollment).order_by(Enrollment.course_id.asc(), Enrollment.student_email.asc(), Enrollment.created_at.asc()).all()
570
+ normalized = 0
571
+ removed = 0
572
+ for e in ens:
573
+ norm = (e.student_email or "").strip().lower()
574
+ if e.student_email != norm:
575
+ e.student_email = norm
576
+ normalized += 1
577
+ commit_with_retry(db)
578
+
579
+ seen = {}
580
+ ens2 = db.query(Enrollment).order_by(Enrollment.course_id.asc(), Enrollment.student_email.asc(), Enrollment.created_at.asc()).all()
581
+ for e in ens2:
582
+ key = (e.course_id, e.student_email)
583
+ if key in seen:
584
+ db.delete(e)
585
+ removed += 1
586
+ else:
587
+ seen[key] = e.id
588
+ commit_with_retry(db)
589
+ return normalized, removed
590
+
591
+
592
+ # ==========================================================
593
+ # Admin login/logout + presença
594
+ # ==========================================================
595
+ def admin_login_ui() -> None:
596
+ st.subheader("🔐 Login do Administrador")
597
+ with st.form("admin_login", clear_on_submit=False):
598
+ u = st.text_input("Usuário", value="", placeholder="admin")
599
+ p = st.text_input("Senha", value="", type="password")
600
+ ok = st.form_submit_button("Entrar", type="primary")
601
+ if ok:
602
+ import hashlib
603
+ if u == ADMIN_USER and (ADMIN_FIXED_PASS_HASH == hashlib.sha256(p.encode()).hexdigest()):
604
+ st.session_state.is_admin = True
605
+ st.session_state.admin_user = u
606
+ st.success("Login realizado.")
607
+ st.rerun()
608
+ else:
609
+ st.error("Credenciais inválidas.")
610
+
611
+ def admin_logout_button() -> None:
612
+ col1, _ = st.columns([1, 5])
613
+ with col1:
614
+ if st.button("Sair", type="secondary"):
615
+ st.session_state.is_admin = False
616
+ st.session_state.admin_user = None
617
+ st.rerun()
618
+
619
+ def _admin_presence_ping(page_label: str):
620
+ role = "admin" if st.session_state.get("is_admin") else "visitante"
621
+ email = None
622
+ nome = st.session_state.get("admin_user") if st.session_state.get("is_admin") else None
623
+ try:
624
+ from core.presence import update_presence
625
+ except Exception:
626
+ from presence import update_presence
627
+ update_presence(role=role, page=page_label, user_email=email, user_name=nome)
628
+
629
+
630
+ # ==========================================================
631
+ # View do Admin
632
+ # ==========================================================
633
+ def render() -> None:
634
+ _admin_presence_ping(page_label="admin_home")
635
+
636
+ if not st.session_state.is_admin:
637
+ admin_login_ui()
638
+ return
639
+
640
+ st.header("🛠️ Painel do Administrador — Pega a Visão")
641
+ admin_logout_button()
642
+
643
+ db = ensure_db_ready()
644
+ try:
645
+ tab_curso, tab_agenda, tab_avaliacao, tab_repos, tab_alunos, tab_turma, tab_interacao, tab_galeria, tab_reset = st.tabs([
646
+ "Cursos & Módulos", "Agenda", "Avaliações & Certificados", "Reposições", "Cadastrar Alunos",
647
+ "Turma em andamento", "👥 Interações", "📷 Galeria de Relatórios", "💾 Reset/Backup"
648
+ ])
649
+
650
+ # ================== CURSOS & MÓDULOS ==================
651
+ with tab_curso:
652
+ st.subheader("Cadastrar curso")
653
+ with st.form("curso_form", clear_on_submit=True):
654
+ titulo = st.text_input("Título do curso")
655
+ desc = st.text_area("Descrição")
656
+ ok_curso = st.form_submit_button("Salvar curso", type="primary")
657
+ if ok_curso:
658
+ if not titulo:
659
+ st.error("Informe um título.")
660
+ else:
661
+ c = Course(title=titulo.strip(), description=desc.strip() if desc else None)
662
+ db.add(c)
663
+ commit_with_retry(db)
664
+ st.success("Curso criado.")
665
+
666
+ st.divider()
667
+ cursos = db.query(Course).order_by(Course.title.asc()).all()
668
+ if not cursos:
669
+ st.info("Nenhum curso.")
670
+ else:
671
+ idx = st.selectbox("Gerenciar curso", options=list(range(len(cursos))), format_func=lambda i: cursos[i].title)
672
+ curso = cursos[idx]
673
+ st.markdown(f"### Curso: **{curso.title}**")
674
+
675
+ with st.expander("Editar curso (nome e descrição)", expanded=False):
676
+ novo_nome = st.text_input("Nome do curso", value=curso.title, key=f"curso_nome_edit_{curso.id}")
677
+ nova_desc = st.text_area("Descrição do curso", value=curso.description or "", key=f"curso_desc_edit_{curso.id}", height=120)
678
+ if st.button("💾 Salvar alterações do curso", key=f"btn_save_curso_{curso.id}"):
679
+ if not novo_nome.strip():
680
+ st.error("Informe um nome válido para o curso.")
681
+ else:
682
+ curso.title = novo_nome.strip()
683
+ curso.description = (nova_desc or "").strip()
684
+ commit_with_retry(db)
685
+ st.success("Curso atualizado com sucesso.")
686
+ st.rerun()
687
+
688
+ up_tabs = st.tabs(["Módulos (vídeo)", "Apostilas (PDF)"])
689
+
690
+ # ---- Módulos (vídeo)
691
+ with up_tabs[0]:
692
+ st.caption("Cadastrar módulo do curso (vídeo opcional).")
693
+ with st.form("add_module", clear_on_submit=True):
694
+ lt = st.text_input("Título do módulo")
695
+ ld = st.text_area("Descrição (opcional)")
696
+ yt_url_raw = st.text_input("URL do vídeo (YouTube — opcional)", placeholder="https://youtu.be/VIDEO_ID ou https://www.youtube.com/shorts/VIDEO_ID")
697
+ f = st.file_uploader("Arquivo de vídeo (opcional) — .mp4/.mkv/.mov/.webm", type=["mp4", "mkv", "mov", "webm"])
698
+ ok = st.form_submit_button("Adicionar módulo")
699
+ if ok:
700
+ if not lt:
701
+ st.error("Informe um título para o módulo.")
702
+ else:
703
+ vpath = None
704
+ url_norm = normalize_youtube_url(yt_url_raw.strip()) if yt_url_raw else None
705
+ if f is not None:
706
+ if url_norm:
707
+ st.info("Arquivo local enviado. A URL do YouTube foi ignorada (prioridade para arquivo local).")
708
+ vpath = save_uploaded_file(f, base_dir="data/videos")
709
+ elif url_norm:
710
+ vpath = url_norm
711
+
712
+ les = Lesson(course_id=curso.id, title=lt.strip(), description=ld.strip() if ld else None, video_path=vpath)
713
+ db.add(les)
714
+ commit_with_retry(db)
715
+ st.success("Módulo adicionado.")
716
+
717
+ st.markdown("#### Módulos cadastrados")
718
+ lessons = db.query(Lesson).filter(Lesson.course_id == curso.id).order_by(Lesson.created_at.asc()).all()
719
+ if not lessons:
720
+ st.caption("Sem módulos cadastrados ainda.")
721
+ else:
722
+ for les in lessons:
723
+ with st.expander(f"🎬 {les.title}", expanded=False):
724
+ new_title = st.text_input("Título do módulo", value=les.title, key=f"mod_title_{les.id}")
725
+ new_desc = st.text_area("Descrição", value=les.description or "", key=f"mod_desc_{les.id}")
726
+ if st.button("💾 Salvar alterações", key=f"mod_save_{les.id}"):
727
+ les.title = (new_title or les.title).strip()
728
+ les.description = (new_desc or "").strip()
729
+ commit_with_retry(db)
730
+ st.success("Módulo atualizado.")
731
+ st.rerun()
732
+
733
+ st.markdown("---")
734
+ st.markdown("**Vídeo do módulo**")
735
+ has_video = bool(les.video_path and (is_url(les.video_path) or os.path.exists(les.video_path)))
736
+ if has_video:
737
+ if is_url(les.video_path):
738
+ st.video(les.video_path)
739
+ st.caption(f"Fonte atual: YouTube ({les.video_path})")
740
+ else:
741
+ st.video(les.video_path)
742
+ st.caption(f"Fonte atual: arquivo local `{os.path.basename(les.video_path)}`")
743
+ else:
744
+ st.info("Nenhum vídeo anexado ainda.")
745
+
746
+ if not has_video:
747
+ up_file = st.file_uploader(
748
+ "Enviar vídeo agora (opcional)",
749
+ type=["mp4", "mkv", "mov", "webm"],
750
+ key=f"mod_upvid_attach_{les.id}"
751
+ )
752
+ url_new_raw = st.text_input(
753
+ "… ou informar URL do YouTube (opcional)",
754
+ key=f"mod_url_attach_{les.id}",
755
+ placeholder="https://youtu.be/VIDEO_ID ou https://www.youtube.com/shorts/VIDEO_ID"
756
+ )
757
+ cols_attach = st.columns([1, 1])
758
+ if cols_attach[0].button("📤 Anexar arquivo de vídeo", key=f"mod_attach_file_{les.id}"):
759
+ if not up_file:
760
+ st.warning("Selecione um arquivo de vídeo.")
761
+ else:
762
+ try:
763
+ new_path = save_uploaded_file(up_file, base_dir="data/videos")
764
+ les.video_path = new_path
765
+ commit_with_retry(db)
766
+ st.success("Vídeo (arquivo) anexado ao módulo.")
767
+ st.rerun()
768
+ except Exception as e:
769
+ st.error(f"Falha ao anexar vídeo: {e}")
770
+ if cols_attach[1].button("🔗 Anexar URL do YouTube", key=f"mod_attach_url_{les.id}"):
771
+ url_norm = normalize_youtube_url(url_new_raw or "")
772
+ if not url_norm or not is_url(url_norm):
773
+ st.warning("Informe uma URL válida do YouTube.")
774
+ else:
775
+ les.video_path = url_norm
776
+ commit_with_retry(db)
777
+ st.success("URL do YouTube anexada ao módulo.")
778
+ st.rerun()
779
+ else:
780
+ up_file = st.file_uploader(
781
+ "Substituir por novo arquivo",
782
+ type=["mp4", "mkv", "mov", "webm"],
783
+ key=f"mod_upvid_replace_{les.id}"
784
+ )
785
+ url_new_raw = st.text_input(
786
+ "… ou substituir por URL do YouTube",
787
+ key=f"mod_url_replace_{les.id}",
788
+ placeholder="https://youtu.be/VIDEO_ID ou https://www.youtube.com/shorts/VIDEO_ID"
789
+ )
790
+ c1, c2, c3 = st.columns([1, 1, 1])
791
+ with c1:
792
+ if up_file and st.button("🔁 Substituir por arquivo", key=f"mod_sendvid_{les.id}"):
793
+ try:
794
+ new_path = save_uploaded_file(up_file, base_dir="data/videos")
795
+ try:
796
+ if les.video_path and not is_url(les.video_path) and os.path.exists(les.video_path):
797
+ os.remove(les.video_path)
798
+ except Exception:
799
+ pass
800
+ les.video_path = new_path
801
+ commit_with_retry(db)
802
+ st.success("Vídeo substituído por arquivo local com sucesso.")
803
+ st.rerun()
804
+ except Exception as e:
805
+ st.error(f"Falha ao substituir vídeo: {e}")
806
+ with c2:
807
+ if st.button("🔁 Substituir por URL do YouTube", key=f"mod_replace_url_{les.id}"):
808
+ url_norm = normalize_youtube_url(url_new_raw or "")
809
+ if not url_norm or not is_url(url_norm):
810
+ st.warning("Informe uma URL válido do YouTube.")
811
+ else:
812
+ try:
813
+ if les.video_path and not is_url(les.video_path) and os.path.exists(les.video_path):
814
+ os.remove(les.video_path)
815
+ except Exception:
816
+ pass
817
+ les.video_path = url_norm
818
+ commit_with_retry(db)
819
+ st.success("Vídeo substituído por URL do YouTube.")
820
+ st.rerun()
821
+ with c3:
822
+ if st.button("🗑️ Remover vídeo (manter módulo)", key=f"mod_rmvid_{les.id}"):
823
+ try:
824
+ if les.video_path and not is_url(les.video_path) and os.path.exists(les.video_path):
825
+ os.remove(les.video_path)
826
+ except Exception:
827
+ pass
828
+ les.video_path = None
829
+ commit_with_retry(db)
830
+ st.success("Vídeo removido do módulo.")
831
+ st.rerun()
832
+
833
+ # Controle de acesso
834
+ st.markdown("---")
835
+ st.markdown("🔒 **Acesso ao vídeo** (somente afeta vídeos; PDFs não são impactados)")
836
+ current_vis = get_video_visibility(les.id)
837
+ vis_label_to_value = {
838
+ "Público (qualquer aluno logado)": "public",
839
+ "Restrito (somente alunos selecionados)": "restricted",
840
+ "Privado (somente Admin)": "private",
841
+ }
842
+ vis_options = list(vis_label_to_value.keys())
843
+ try:
844
+ default_idx = vis_options.index(
845
+ [lbl for lbl, val in vis_label_to_value.items() if val == current_vis][0]
846
+ )
847
+ except Exception:
848
+ default_idx = 0
849
+ vis_sel_label = st.selectbox(
850
+ "Visibilidade",
851
+ options=vis_options,
852
+ index=default_idx,
853
+ key=f"vid_vis_{les.id}"
854
+ )
855
+ vis_value = vis_label_to_value[vis_sel_label]
856
+
857
+ ens_list = db.query(Enrollment).filter(Enrollment.course_id == curso.id).order_by(Enrollment.student_name.asc()).all()
858
+ alunos_labels = [f"{e.student_name} <{e.student_email}>" for e in ens_list]
859
+ alunos_map = {f"{e.student_name} <{e.student_email}>": e.student_email for e in ens_list}
860
+
861
+ allowed_emails = set(get_video_acl_emails(les.id))
862
+ preselected_labels = [lbl for lbl in alunos_labels if alunos_map[lbl] in allowed_emails]
863
+
864
+ if vis_value == "restricted":
865
+ sel_labels = st.multiselect(
866
+ "Selecione os alunos autorizados a assistir este vídeo",
867
+ options=alunos_labels,
868
+ default=preselected_labels,
869
+ key=f"vid_acl_{les.id}"
870
+ )
871
+ else:
872
+ sel_labels = []
873
+
874
+ cva1, cva2 = st.columns([1, 1])
875
+ if cva1.button("💾 Salvar visibilidade", key=f"btn_save_vis_{les.id}"):
876
+ try:
877
+ set_video_visibility(les.id, vis_value)
878
+ st.success("Visibilidade do vídeo atualizada.")
879
+ except Exception as e:
880
+ st.error(f"Falha ao salvar visibilidade: {e}")
881
+
882
+ if vis_value == "restricted":
883
+ if cva2.button("💾 Salvar lista de alunos autorizados", key=f"btn_save_acl_{les.id}"):
884
+ try:
885
+ emails_new = [alunos_map[lbl] for lbl in sel_labels]
886
+ set_video_acl_emails(les.id, emails_new)
887
+ st.success("Lista de alunos autorizada atualizada.")
888
+ except Exception as e:
889
+ st.error(f"Falha ao salvar lista de alunos: {e}")
890
+ else:
891
+ st.caption("Para definir alunos específicos, selecione a visibilidade **Restrito**.")
892
+
893
+ st.markdown("---")
894
+ if st.button("❌ Excluir módulo", key=f"del_mod_{les.id}"):
895
+ try:
896
+ if les.video_path and not is_url(les.video_path) and os.path.exists(les.video_path):
897
+ os.remove(les.video_path)
898
+ except Exception:
899
+ pass
900
+ db.delete(les)
901
+ commit_with_retry(db)
902
+ st.success("Módulo removido.")
903
+ st.rerun()
904
+
905
+ # ---- Apostilas (PDF)
906
+ with up_tabs[1]:
907
+ st.caption("Adicionar apostila (PDF) ao curso")
908
+ with st.form("add_mat", clear_on_submit=True):
909
+ mt = st.text_input("Título da apostila")
910
+ pf = st.file_uploader("Arquivo PDF", type=["pdf"])
911
+ okm = st.form_submit_button("Adicionar")
912
+ if okm:
913
+ if not mt or not pf:
914
+ st.error("Informe título e selecione um PDF.")
915
+ else:
916
+ ppath = save_uploaded_file(pf, base_dir="data/pdfs")
917
+ m = Material(course_id=curso.id, title=mt.strip(), pdf_path=ppath)
918
+ db.add(m)
919
+ commit_with_retry(db)
920
+ st.success("Apostila adicionada.")
921
+
922
+ st.markdown("#### Apostilas cadastradas")
923
+ mats = db.query(Material).filter(Material.course_id == curso.id).order_by(Material.created_at.asc()).all()
924
+ for m in mats:
925
+ cols = st.columns([4, 2, 1])
926
+ cols[0].write(f"📄 **{m.title}**")
927
+ if m.pdf_path and os.path.exists(m.pdf_path):
928
+ try:
929
+ with open(m.pdf_path, "rb") as f:
930
+ cols[1].download_button("Baixar", data=f.read(), file_name=os.path.basename(m.pdf_path), key=f"dl_mat_{m.id}")
931
+ except Exception:
932
+ cols[1].warning("Falha ao abrir PDF.")
933
+ else:
934
+ cols[1].warning("Arquivo não encontrado.")
935
+ if cols[2].button("Excluir", key=f"del_mat_{m.id}"):
936
+ try:
937
+ if m.pdf_path and os.path.exists(m.pdf_path):
938
+ os.remove(m.pdf_path)
939
+ except Exception:
940
+ pass
941
+ db.delete(m)
942
+ commit_with_retry(db)
943
+ st.success("Apostila removida.")
944
+ st.rerun()
945
+
946
+ # ================== AGENDA (CRUD + Calendário) ==================
947
+ with tab_agenda:
948
+ st.subheader("Agenda por curso")
949
+ cursos_all = db.query(Course).order_by(Course.title.asc()).all()
950
+ if not cursos_all:
951
+ st.info("Cadastre um curso primeiro.")
952
+ else:
953
+ cidx = st.selectbox("Curso", options=list(range(len(cursos_all))), format_func=lambda i: cursos_all[i].title, key="agenda_sel_curso")
954
+ curso_ag = cursos_all[cidx]
955
+
956
+ lessons = db.query(Lesson).filter(Lesson.course_id == curso_ag.id).order_by(Lesson.created_at.asc()).all()
957
+ ens = db.query(Enrollment).filter(Enrollment.course_id == curso_ag.id).order_by(Enrollment.student_name.asc()).all()
958
+
959
+ with st.expander("📥 Importar Agenda (TSV/CSV/TXT/Excel ou texto colado)", expanded=False):
960
+ st.caption("Formato: **Semana, Data, Dia, Horário, Ocupação, Aluno, Mat., Descrição, Tema**.")
961
+
962
+ col_up, col_paste = st.columns(2)
963
+ uploaded = col_up.file_uploader("Enviar arquivo", type=["csv","tsv","txt","xlsx","xls"], key=f"imp_ag_up_{curso_ag.id}")
964
+ pasted_text = col_paste.text_area("… ou cole aqui o conteúdo tabulado (TSV)", height=220, key=f"imp_ag_txt_{curso_ag.id}")
965
+
966
+ try_link_module = st.checkbox("Vincular módulo automaticamente pelo TEMA (título exato)", value=True, key=f"imp_ag_trylink_{curso_ag.id}")
967
+
968
+ btn_preview = st.button("🔍 Pré-visualizar", key=f"imp_ag_preview_{curso_ag.id}")
969
+ df_raw, df_norm = None, None
970
+
971
+ if btn_preview:
972
+ try:
973
+ if uploaded is not None:
974
+ df_raw = _read_agenda_uploaded(uploaded)
975
+ elif pasted_text.strip():
976
+ df_raw = _parse_tsv_text(pasted_text)
977
+ else:
978
+ st.warning("Envie um arquivo **ou** cole o texto tabulado.")
979
+ if df_raw is not None and not df_raw.empty:
980
+ st.success(f"Dados lidos. Linhas: {len(df_raw)}")
981
+ with st.container():
982
+ st.markdown("**Prévia (dados brutos)**")
983
+ st.dataframe(df_raw.head(15), use_container_width=True)
984
+
985
+ df_norm = _clean_agenda_df(df_raw)
986
+ if df_norm.empty:
987
+ st.warning("Não foi possível normalizar. Verifique o cabeçalho e o conteúdo.")
988
+ else:
989
+ preview_cols = ['semana','data','dia','horario','inicio_hhmm','fim_hhmm','ocupacao','aluno','matricula','tema','fora_do_cronograma','vago']
990
+ for c in preview_cols:
991
+ if c not in df_norm.columns:
992
+ df_norm[c] = ""
993
+ st.subheader("✅ Prévia normalizada")
994
+ st.dataframe(df_norm[preview_cols], use_container_width=True, hide_index=True)
995
+
996
+ st.session_state[f"imp_df_norm_{curso_ag.id}"] = df_norm.to_dict(orient='list')
997
+ else:
998
+ st.info("Sem dados para pré-visualizar.")
999
+ except Exception as e:
1000
+ st.error(f"Falha ao pré-visualizar: {e}")
1001
+
1002
+ btn_import = st.button("📦 Importar para este curso", key=f"imp_ag_do_{curso_ag.id}")
1003
+ if btn_import:
1004
+ payload = st.session_state.get(f"imp_df_norm_{curso_ag.id}")
1005
+ if not payload:
1006
+ st.warning("Faça a pré-visualização primeiro.")
1007
+ else:
1008
+ try:
1009
+ df_norm = pd.DataFrame(payload)
1010
+
1011
+ lessons_by_title_norm = { _norm(l.title): l for l in lessons }
1012
+ enrolls_by_name_norm = { _norm(e.student_name): e for e in ens }
1013
+
1014
+ agenda_exist = db.query(Schedule).filter(Schedule.course_id == curso_ag.id).all()
1015
+
1016
+ def _key_ev(a: Schedule, meta: Dict[str,Any]) -> tuple:
1017
+ topic = meta.get("topic") or ""
1018
+ emails = meta.get("assigned_emails") or []
1019
+ em = (emails[0] if emails else "").strip().lower()
1020
+ return (a.class_date, a.start_time, a.end_time, topic.strip().lower(), em)
1021
+
1022
+ exist_keys = set()
1023
+ for a in agenda_exist:
1024
+ m = parse_schedule_topic(a.topic)
1025
+ exist_keys.add(_key_ev(a, m))
1026
+
1027
+ created, skipped = 0, 0
1028
+ for _, r in df_norm.iterrows():
1029
+ d = r.get('data')
1030
+ ini = r.get('inicio_hhmm')
1031
+ fim = r.get('fim_hhmm')
1032
+ tema = (r.get('tema') or "").strip()
1033
+ ocup = (r.get('ocupacao') or "").strip()
1034
+ aluno_nome = (r.get('aluno') or "").strip()
1035
+ vago = bool(r.get('vago'))
1036
+ semana = r.get('semana') or None
1037
+ details = (r.get('descricao') or "").strip()
1038
+ fora = bool(r.get('fora_do_cronograma'))
1039
+
1040
+ if pd.isna(d) or not ini or not fim:
1041
+ skipped += 1
1042
+ continue
1043
+
1044
+ t1, t2 = parse_time_range(f"{ini}-{fim}")
1045
+ if not t1 or not t2:
1046
+ skipped += 1
1047
+ continue
1048
+
1049
+ assigned = []
1050
+ if not vago and aluno_nome:
1051
+ e = enrolls_by_name_norm.get(_norm(aluno_nome))
1052
+ if e:
1053
+ assigned = [e.student_email.strip().lower()]
1054
+
1055
+ module_id = None
1056
+ if try_link_module and tema:
1057
+ l = lessons_by_title_norm.get(_norm(tema))
1058
+ if l:
1059
+ module_id = l.id
1060
+
1061
+ meta_obj = {
1062
+ "topic": tema or None,
1063
+ "module_id": module_id,
1064
+ "assigned_emails": assigned,
1065
+ "occupancy": ocup,
1066
+ "module_index": None,
1067
+ "details": details or None,
1068
+ "descricao": details or None,
1069
+ "semana": semana,
1070
+ "off_schedule": fora,
1071
+ "aluno_nome": (aluno_nome or None),
1072
+ "matricula": r.get('matricula'),
1073
+ }
1074
+ topic_json = json.dumps(meta_obj, ensure_ascii=False)
1075
+
1076
+ key = (pd.to_datetime(d).date(), t1, t2, (tema or "").strip().lower(), (assigned[0] if assigned else ""))
1077
+ if key in exist_keys:
1078
+ skipped += 1
1079
+ continue
1080
+
1081
+ ag = Schedule(
1082
+ course_id=curso_ag.id,
1083
+ class_date=pd.to_datetime(d).date(),
1084
+ start_time=t1,
1085
+ end_time=t2,
1086
+ topic=topic_json
1087
+ )
1088
+ db.add(ag)
1089
+ commit_with_retry(db)
1090
+ exist_keys.add(key)
1091
+ created += 1
1092
+
1093
+ st.session_state.cal_ver += 1
1094
+ st.success(f"Importação concluída. Criados: {created} · Ignorados (duplicados ou inválidos): {skipped}")
1095
+ st.rerun()
1096
+
1097
+ except Exception as e:
1098
+ db.rollback()
1099
+ st.error(f"Falha ao importar: {e}")
1100
+
1101
+ with st.form("agenda_add", clear_on_submit=True):
1102
+ d = st.date_input("Data da aula")
1103
+ colh1, colh2 = st.columns(2)
1104
+ t1 = colh1.time_input("Início", value=time(19, 0))
1105
+ t2 = colh2.time_input("Fim", value=time(20, 0))
1106
+ mod_opt = st.selectbox("Vincular a um módulo (opcional)", options=["— sem vínculo —"] + [f"[{i+1}] {l.title}" for i, l in enumerate(lessons)])
1107
+ alunos_opts = [f"{e.student_name} <{e.student_email}>" for e in ens]
1108
+ alunos_sel = st.multiselect("Atribuir alunos (opcional)", options=alunos_opts)
1109
+ ocup = st.text_input("Ocupação (ex.: AO VIVO, Gravado…) (opcional)", value="")
1110
+ mod_index = st.text_input("Índice do módulo (opcional)", value="")
1111
+ tema_manual = st.text_input("Tema/descrição (caso não vincule módulo)", value="")
1112
+ ok_add = st.form_submit_button("Adicionar à agenda", type="primary")
1113
+ if ok_add:
1114
+ try:
1115
+ module_id = None
1116
+ if mod_opt != "— sem vínculo —":
1117
+ idx_mod = int(mod_opt.split("]")[0].replace("[",""))
1118
+ module_id = lessons[idx_mod-1].id
1119
+ emails = [re.search(r"<(.+?)>", s).group(1).strip().lower() for s in alunos_sel] if alunos_sel else []
1120
+ topic_obj = {
1121
+ "topic": (tema_manual.strip() if tema_manual.strip() else None),
1122
+ "module_id": module_id,
1123
+ "assigned_emails": emails,
1124
+ "occupancy": ocup.strip(),
1125
+ "module_index": (mod_index.strip() or None),
1126
+ }
1127
+ ag = Schedule(
1128
+ course_id=curso_ag.id,
1129
+ class_date=d,
1130
+ start_time=t1,
1131
+ end_time=t2,
1132
+ topic=json.dumps(topic_obj, ensure_ascii=False),
1133
+ )
1134
+ db.add(ag)
1135
+ commit_with_retry(db)
1136
+ st.success("Aula adicionada à agenda.")
1137
+ st.rerun()
1138
+ except Exception as e:
1139
+ st.error(f"Falha ao adicionar à agenda: {e}")
1140
+
1141
+ st.markdown("#### Itens da agenda")
1142
+ agenda = db.query(Schedule).filter(Schedule.course_id == curso_ag.id).order_by(Schedule.class_date.asc(), Schedule.start_time.asc()).all()
1143
+ if not agenda:
1144
+ st.info("Sem agenda cadastrada.")
1145
+ else:
1146
+ lessons_by_id = {l.id: l for l in lessons}
1147
+ rows = []
1148
+ for a in agenda:
1149
+ meta = parse_schedule_topic(a.topic)
1150
+ mod = lessons_by_id.get(meta.get("module_id")) if meta.get("module_id") else None
1151
+ rows.append({
1152
+ "ID": a.id,
1153
+ "Data": a.class_date.strftime("%d/%m/%Y") if a.class_date else "",
1154
+ "Início": a.start_time.strftime("%H:%M") if a.start_time else "",
1155
+ "Fim": a.end_time.strftime("%H:%M") if a.end_time else "",
1156
+ "Módulo/Assunto": (mod.title if mod else (meta.get("topic") or "—")),
1157
+ "Alunos": ", ".join(meta.get("assigned_emails") or []),
1158
+ "Ocupação": meta.get("occupancy") or "",
1159
+ })
1160
+ st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)
1161
+
1162
+ col_del1, col_del2 = st.columns([1,3])
1163
+ del_id = col_del1.number_input("ID para excluir", min_value=0, value=0, step=1, key="agenda_del_id")
1164
+ if col_del2.button("🗑️ Excluir item da agenda", disabled=(del_id<=0), key="agenda_btn_del"):
1165
+ item = db.query(Schedule).filter(Schedule.id == int(del_id)).first()
1166
+ if not item:
1167
+ st.warning("ID não encontrado.")
1168
+ else:
1169
+ db.delete(item)
1170
+ commit_with_retry(db)
1171
+ st.success("Item excluído.")
1172
+ st.rerun()
1173
+
1174
+ st.markdown("#### Calendário")
1175
+ events, color_map = build_fullcalendar_events(agenda, lessons_by_id)
1176
+ events = json_sanitize_events(events)
1177
+ cal_options = {
1178
+ "initialView": "dayGridMonth",
1179
+ "locale": "pt-br",
1180
+ "height": 740,
1181
+ "headerToolbar": {
1182
+ "left": "prev,next today",
1183
+ "center": "title",
1184
+ "right": "dayGridMonth,timeGridWeek,listWeek"
1185
+ },
1186
+ }
1187
+ render_calendar(events=events, options=cal_options, key=f"adm_cal_{curso_ag.id}_{st.session_state.cal_ver}")
1188
+
1189
+ # ================== AVALIAÇÕES & CERTIFICADOS ==================
1190
+ with tab_avaliacao:
1191
+ st.subheader("Notas e Certificados")
1192
+ cursos_all = db.query(Course).order_by(Course.title.asc()).all()
1193
+ if not cursos_all:
1194
+ st.info("Cadastre um curso primeiro.")
1195
+ else:
1196
+ cidx = st.selectbox("Curso", options=list(range(len(cursos_all))), format_func=lambda i: cursos_all[i].title, key="av_sel_curso")
1197
+ curso_av = cursos_all[cidx]
1198
+ ens = db.query(Enrollment).filter(Enrollment.course_id == curso_av.id).order_by(Enrollment.student_name.asc()).all()
1199
+ if not ens:
1200
+ st.info("Cadastre alunos neste curso para lançar notas e emitir certificados.")
1201
+ else:
1202
+ nomes = [f"{e.student_name} <{e.student_email}>" for e in ens]
1203
+ # ---- Notas
1204
+ st.markdown("### 📝 Lançar nota")
1205
+ with st.form("grade_form", clear_on_submit=True):
1206
+ who = st.selectbox("Aluno", options=nomes)
1207
+ nota = st.number_input("Nota", min_value=0.0, max_value=10.0, step=0.1)
1208
+ obs = st.text_area("Observações (opcional)")
1209
+ okg = st.form_submit_button("Salvar nota", type="primary")
1210
+ if okg:
1211
+ email = re.search(r"<(.+?)>", who).group(1).strip().lower()
1212
+ nome = who.split(" <")[0].strip()
1213
+ g = Grade(course_id=curso_av.id, student_name=nome, student_email=email, grade=float(nota), note=(obs.strip() or None))
1214
+ db.add(g)
1215
+ commit_with_retry(db)
1216
+ st.success("Nota lançada.")
1217
+
1218
+ grades = db.query(Grade).filter(Grade.course_id == curso_av.id).order_by(Grade.created_at.desc()).all()
1219
+ if grades:
1220
+ df_g = pd.DataFrame([{"ID":g.id,"Aluno":g.student_name,"E-mail":g.student_email,"Nota":g.grade,"Obs":g.note,"Data":g.created_at} for g in grades])
1221
+ st.dataframe(df_g, use_container_width=True, hide_index=True)
1222
+
1223
+ st.markdown("---")
1224
+ # ---- Certificados
1225
+ st.markdown("### 🎓 Emitir certificado")
1226
+ with st.form("cert_form", clear_on_submit=True):
1227
+ who2 = st.selectbox("Aluno", options=nomes, key="cert_who")
1228
+ nome_c = st.text_input("Nome no certificado (como deve aparecer)", value=who2.split(" <")[0].strip())
1229
+ okc = st.form_submit_button("Emitir certificado (PDF)", type="primary")
1230
+ if okc:
1231
+ try:
1232
+ email_c = re.search(r"<(.+?)>", who2).group(1).strip().lower()
1233
+ out_dir = os.path.join("data","certificates")
1234
+ os.makedirs(out_dir, exist_ok=True)
1235
+ pdf_path = generate_certificate_pdf(course_title=curso_av.title, student_name=nome_c, output_dir=out_dir)
1236
+ cert = Certificate(course_id=curso_av.id, student_name=nome_c, student_email=email_c, pdf_path=pdf_path, issued_at=datetime.utcnow())
1237
+ db.add(cert)
1238
+ commit_with_retry(db)
1239
+ st.success("Certificado emitido.")
1240
+ with open(pdf_path,"rb") as f:
1241
+ st.download_button("⬇️ Baixar certificado agora", data=f.read(), file_name=os.path.basename(pdf_path), key=f"dl_newcert_{curso_av.id}_{email_c}")
1242
+ except Exception as e:
1243
+ st.error(f"Falha ao emitir certificado: {e}")
1244
+
1245
+ certs = db.query(Certificate).filter(Certificate.course_id == curso_av.id).order_by(Certificate.issued_at.desc()).all()
1246
+ if certs:
1247
+ df_c = pd.DataFrame([{"ID":c.id,"Aluno":c.student_name,"E-mail":c.student_email,"Arquivo":os.path.basename(c.pdf_path) if c.pdf_path else "—","Emitido em":c.issued_at} for c in certs])
1248
+ st.dataframe(df_c, use_container_width=True, hide_index=True)
1249
+
1250
+ # ================== REPOSIÇÕES ==================
1251
+ with tab_repos:
1252
+ st.subheader("Solicitações de reposição")
1253
+ cursos_all = db.query(Course).order_by(Course.title.asc()).all()
1254
+ if not cursos_all:
1255
+ st.info("Cadastre um curso primeiro.")
1256
+ else:
1257
+ cidx = st.selectbox("Curso", options=list(range(len(cursos_all))), format_func=lambda i: cursos_all[i].title, key="rep_sel_curso")
1258
+ curso_rp = cursos_all[cidx]
1259
+ reqs = db.query(MakeupRequest).filter(MakeupRequest.course_id == curso_rp.id).order_by(MakeupRequest.created_at.desc()).all()
1260
+ if not reqs:
1261
+ st.info("Sem solicitações para este curso.")
1262
+ else:
1263
+ for r in reqs:
1264
+ with st.expander(f"{r.student_name} <{r.student_email}> — {r.requested_date} — status: {r.status}", expanded=False):
1265
+ st.write(r.note or "Sem observações.")
1266
+ c1, c2 = st.columns([1,3])
1267
+ new_status = c1.selectbox("Novo status", options=["pending","approved","denied"], index=["pending","approved","denied"].index(r.status), key=f"rp_status_{r.id}")
1268
+ new_note = c2.text_input("Nota interna (opcional)", value=r.note or "", key=f"rp_note_{r.id}")
1269
+ if st.button("💾 Atualizar solicitação", key=f"rp_save_{r.id}"):
1270
+ r.status = new_status
1271
+ r.note = (new_note or "").strip() or None
1272
+ commit_with_retry(db)
1273
+ st.success("Solicitação atualizada.")
1274
+ st.rerun()
1275
+
1276
+ # ================== CADASTRAR ALUNOS ==================
1277
+ with tab_alunos:
1278
+ st.subheader("Matrículas por curso")
1279
+ cursos_all = db.query(Course).order_by(Course.title.asc()).all()
1280
+ if not cursos_all:
1281
+ st.info("Cadastre um curso primeiro.")
1282
+ else:
1283
+ cidx = st.selectbox("Curso", options=list(range(len(cursos_all))), format_func=lambda i: cursos_all[i].title, key="aluno_sel_curso")
1284
+ curso_en = cursos_all[cidx]
1285
+
1286
+ st.markdown("### ➕ Adicionar matrícula")
1287
+ with st.form("matricula_add", clear_on_submit=True):
1288
+ nome = st.text_input("Nome do aluno")
1289
+ email = st.text_input("E-mail do aluno").strip().lower()
1290
+ ok_en = st.form_submit_button("Matricular", type="primary")
1291
+ if ok_en:
1292
+ if not nome or not email:
1293
+ st.error("Preencha nome e e-mail.")
1294
+ else:
1295
+ e = Enrollment(course_id=curso_en.id, student_name=nome.strip(), student_email=email.strip().lower())
1296
+ db.add(e)
1297
+ commit_with_retry(db)
1298
+ st.success("Aluno matriculado.")
1299
+ st.rerun()
1300
+
1301
+ st.markdown("### Alunos matriculados")
1302
+ ens = db.query(Enrollment).filter(Enrollment.course_id == curso_en.id).order_by(Enrollment.created_at.desc()).all()
1303
+ if not ens:
1304
+ st.info("Nenhum aluno neste curso.")
1305
+ else:
1306
+ for e in ens:
1307
+ cols = st.columns([3,3,2,2,2])
1308
+ cols[0].write(f"**{e.student_name}**")
1309
+ cols[1].write(e.student_email)
1310
+ with cols[2]:
1311
+ with st.expander("🔑 Definir/Resetar senha", expanded=False):
1312
+ pwd = st.text_input("Nova senha", type="password", key=f"setpwd_{e.id}")
1313
+ if st.button("Salvar senha", key=f"btn_setpwd_{e.id}"):
1314
+ try:
1315
+ set_student_password(e.student_email, pwd)
1316
+ st.success("Senha definida.")
1317
+ except Exception as ex:
1318
+ st.error(f"Erro ao salvar senha: {ex}")
1319
+ if cols[3].button("🗑️ Remover", key=f"del_en_{e.id}"):
1320
+ db.delete(e)
1321
+ commit_with_retry(db)
1322
+ st.success("Matrícula removida.")
1323
+ st.rerun()
1324
+ if cols[4].button("🧹 Normalizar & deduplicar", key=f"normdedup_{e.id}"):
1325
+ n, r = normalize_and_dedup_enrollments(db)
1326
+ st.success(f"Normalizados: {n}, apagados duplicados: {r}")
1327
+ st.rerun()
1328
+
1329
+ # ================== TURMA EM ANDAMENTO (ADMIN) ==================
1330
+ with tab_turma:
1331
+ st.subheader("Turma em andamento (visão do Admin)")
1332
+ cursos_all = db.query(Course).order_by(Course.title.asc()).all()
1333
+ if not cursos_all:
1334
+ st.info("Cadastre um curso primeiro.")
1335
+ else:
1336
+ cidx = st.selectbox("Curso", options=list(range(len(cursos_all))), format_func=lambda i: cursos_all[i].title, key="turma_sel_curso")
1337
+ curso_tx = cursos_all[cidx]
1338
+ lessons = db.query(Lesson).filter(Lesson.course_id == curso_tx.id).all()
1339
+ agenda = db.query(Schedule).filter(Schedule.course_id == curso_tx.id).order_by(Schedule.class_date.asc(), Schedule.start_time.asc()).all()
1340
+
1341
+ lessons_by_id = {l.id: l for l in lessons}
1342
+ rows = []
1343
+ for a in agenda:
1344
+ meta = parse_schedule_topic(a.topic)
1345
+ mod = lessons_by_id.get(meta.get("module_id")) if meta.get("module_id") else None
1346
+ title = mod.title if mod else (meta.get("topic") or "—")
1347
+ rows.append({
1348
+ "Data": a.class_date,
1349
+ "Início": a.start_time.strftime("%H:%M") if a.start_time else "",
1350
+ "Fim": a.end_time.strftime("%H:%M") if a.end_time else "",
1351
+ "Aula": title,
1352
+ "Alunos": ", ".join(meta.get("assigned_emails") or []),
1353
+ "Ocupação": meta.get("occupancy") or "",
1354
+ })
1355
+ if rows:
1356
+ st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)
1357
+ else:
1358
+ st.info("Sem agenda cadastrada.")
1359
+
1360
+ st.markdown("#### Calendário")
1361
+ events, color_map = build_fullcalendar_events(agenda, lessons_by_id)
1362
+ events = json_sanitize_events(events)
1363
+ cal_options = {
1364
+ "initialView": "listWeek",
1365
+ "locale": "pt-br",
1366
+ "height": 640,
1367
+ "headerToolbar": {
1368
+ "left": "prev,next today",
1369
+ "center": "title",
1370
+ "right": "dayGridMonth,timeGridWeek,listWeek"
1371
+ },
1372
+ }
1373
+ render_calendar(events=events, options=cal_options, key=f"adm_turma_cal_{curso_tx.id}_{st.session_state.cal_ver}")
1374
+
1375
+ # ================== INTERAÇÕES (PRESENÇA + COMENTÁRIOS) ==================
1376
+ with tab_interacao:
1377
+ st.subheader("👥 Usuários online (últimos N segundos)")
1378
+ secs = int(st.number_input("Threshold (segundos)", min_value=30, max_value=3600, value=PRESENCE_ONLINE_THRESHOLD_SEC, step=30))
1379
+ dfp = get_online_users(threshold_sec=secs)
1380
+ if dfp is None or dfp.empty:
1381
+ st.info("Ninguém online neste momento dentro do threshold.")
1382
+ else:
1383
+ dfv = dfp.copy()
1384
+ dfv["Tempo de sessão"] = dfv["session_sec"].apply(_fmt_duration)
1385
+ dfv["Inatividade"] = dfv["idle_sec"].apply(_fmt_duration)
1386
+ dfv.rename(columns={"user_email":"E-mail","user_name":"Nome","role":"Perfil","page":"Página","first_seen":"Primeiro acesso","last_seen":"Última ação"}, inplace=True)
1387
+ st.dataframe(
1388
+ dfv[["Nome","E-mail","Perfil","Página","Primeiro acesso","Última ação","Tempo de sessão","Inatividade"]],
1389
+ use_container_width=True, hide_index=True
1390
+ )
1391
+
1392
+ st.markdown("---")
1393
+ st.subheader("💬 Moderação de comentários")
1394
+ cursos = db.query(Course).order_by(Course.title.asc()).all()
1395
+ if not cursos:
1396
+ st.info("Cadastre um curso primeiro para ver comentários.")
1397
+ else:
1398
+ idxc = st.selectbox("Curso", options=list(range(len(cursos))), format_func=lambda i: cursos[i].title, key="adm_curso_coment")
1399
+ curso_sel = cursos[idxc]
1400
+ dft = get_comments(curso_sel.id)
1401
+ if dft is None or dft.empty:
1402
+ st.info("Sem comentários neste curso.")
1403
+ else:
1404
+ st.dataframe(dft, use_container_width=True)
1405
+ del_id = st.number_input("ID para excluir (apaga também respostas)", min_value=0, value=0, step=1)
1406
+ if st.button("🗑️ Excluir comentário selecionado", disabled=(del_id <= 0)):
1407
+ try:
1408
+ delete_comment(int(del_id))
1409
+ st.success("Comentário excluído.")
1410
+ st.rerun()
1411
+ except Exception as e:
1412
+ st.error(f"Falha ao excluir: {e}")
1413
+
1414
+ # ================== GALERIA DE RELATÓRIOS (ADMIN) ==================
1415
+ with tab_galeria:
1416
+ st.subheader("📷 Galeria de Relatórios (Admin)")
1417
+ aba_galeria_relatorios(context_key="admin_")
1418
+
1419
+ # ================== RESET DA BASE + BACKUP/RESTORE ==================
1420
+ with tab_reset:
1421
+ st.subheader("💾 Backup & Restore do Banco e Mídias")
1422
+
1423
+ # ---------- SYNC COM HUGGING FACE (DATASET) ----------
1424
+ st.markdown("### ☁️ Backup para Hugging Face (Dataset)")
1425
+ st.caption("Envia snapshot do **db.sqlite** e um **ZIP** de **data/** para um repositório Dataset no Hugging Face. Requer **HF_TOKEN**.")
1426
+
1427
+ default_repo = st.session_state.get("hf_dataset_repo") or "Roudrigus/minha-academia-db"
1428
+ repo_id_raw = st.text_input("Repo Dataset (ex.: Owner/Nome)", value=default_repo, key="hf_repo_id")
1429
+ repo_id = _sanitize_repo_id(repo_id_raw)
1430
+ if repo_id != repo_id_raw:
1431
+ st.info(f"Repo ajustado para **{repo_id}** (sanitizado).")
1432
+
1433
+ colhfa, colhfb, colhfc = st.columns(3)
1434
+ with colhfa:
1435
+ st.markdown("**Biblioteca**")
1436
+ if HF_HUB_AVAILABLE:
1437
+ st.success("📦 huggingface_hub disponível")
1438
+ else:
1439
+ st.warning("📦 huggingface_hub NÃO instalado. Adicione no requirements.txt: `huggingface_hub>=0.21.4`")
1440
+ with colhfb:
1441
+ st.markdown("**Token**")
1442
+ has_token = bool((os.environ.get("HF_TOKEN") or "").strip())
1443
+ if has_token:
1444
+ st.success("🔑 HF_TOKEN definido")
1445
+ else:
1446
+ st.warning("🔑 HF_TOKEN ausente (Settings → Variables)")
1447
+ with colhfc:
1448
+ st.markdown("**Repositório**")
1449
+ if repo_id and "/" in repo_id:
1450
+ st.success(f"🗃️ {repo_id}")
1451
+ else:
1452
+ st.warning("Informe como `Owner/Nome`")
1453
+
1454
+ do_sync = st.button("☁️ Sincronizar no Hugging Face (Dataset)", key="btn_sync_now")
1455
+ if do_sync:
1456
+ if not HF_HUB_AVAILABLE:
1457
+ st.error("Instale huggingface_hub e reinicie o app.")
1458
+ elif not has_token:
1459
+ st.error("Defina o secret HF_TOKEN no ambiente para prosseguir.")
1460
+ elif not repo_id or "/" not in repo_id:
1461
+ st.error("Informe um repo válido no formato `Owner/Nome`.")
1462
+ else:
1463
+ try:
1464
+ st.session_state["hf_dataset_repo"] = repo_id.strip()
1465
+ stats = sync_to_hf_dataset(dataset_repo=repo_id.strip(), db_path=DB_PATH, data_dir="data")
1466
+ msgs = []
1467
+ if stats.get("db_uploaded"):
1468
+ msgs.append("db.sqlite")
1469
+ if stats.get("data_uploaded"):
1470
+ msgs.append("data.zip")
1471
+ if msgs:
1472
+ st.success(f"Backup enviado: {', '.join(msgs)} → {repo_id}")
1473
+ else:
1474
+ st.info("Nada para enviar (db.sqlite não encontrado e pasta data/ inexistente).")
1475
+ except Exception as e:
1476
+ st.error(f"Falha ao sincronizar: {e}")
1477
+ st.caption("Stacktrace (debug):")
1478
+ st.code(traceback.format_exc())
1479
+
1480
+ st.markdown("---")
1481
+ # ---------- BACKUP AUTOMÁTICO ----------
1482
+ st.markdown("### ⏱️ Backup automático (inteligente, a cada 10 min)")
1483
+ enable_auto = st.checkbox("Habilitar backup automático (10 min)", value=st.session_state.get("auto_bkp_enabled", False))
1484
+ st.session_state["auto_bkp_enabled"] = enable_auto
1485
+
1486
+ now_ts = _time.time()
1487
+ last_ts = st.session_state.get("auto_bkp_last_ts", 0.0)
1488
+ next_in = max(0, int(AUTO_BKP_INTERVAL_SEC - (now_ts - last_ts))) if enable_auto else None
1489
+
1490
+ cstat1, cstat2, cstat3 = st.columns(3)
1491
+ with cstat1:
1492
+ st.metric("Intervalo", "10 min")
1493
+ with cstat2:
1494
+ st.metric("Próxima execução", f"{next_in}s" if enable_auto else "—")
1495
+ with cstat3:
1496
+ last_status = st.session_state.get("auto_bkp_last_status","—")
1497
+ st.metric("Último ciclo", last_status)
1498
+
1499
+ if enable_auto and HF_HUB_AVAILABLE and has_token and repo_id and "/" in repo_id:
1500
+ if now_ts - last_ts >= AUTO_BKP_INTERVAL_SEC:
1501
+ try:
1502
+ status = _auto_backup_tick(repo_id)
1503
+ st.session_state["auto_bkp_last_status"] = status
1504
+ st.session_state["auto_bkp_last_ts"] = now_ts
1505
+ st.success(f"Auto-backup: {status}")
1506
+ st.rerun()
1507
+ except Exception as e:
1508
+ st.session_state["auto_bkp_last_status"] = f"erro: {e}"
1509
+ st.error(f"Auto-backup falhou: {e}")
1510
+
1511
+ st.caption("Obs.: o auto-backup executa no render do painel Admin. Mantenha esta aba aberta.")
1512
+
1513
+ st.markdown("### Backup do Banco (.sqlite)")
1514
+ if os.path.exists(DB_PATH):
1515
+ with open(DB_PATH, "rb") as f:
1516
+ st.download_button(
1517
+ "⬇️ Baixar banco (SQLite)",
1518
+ data=f.read(),
1519
+ file_name="db_backup.sqlite",
1520
+ mime="application/octet-stream",
1521
+ )
1522
+ else:
1523
+ st.info("Banco ainda não existe no disco (será criado ao salvar dado).")
1524
+
1525
+ st.markdown("### Backup em CSV de todas as tabelas")
1526
+ db2 = ensure_db_ready()
1527
+ try:
1528
+ cur_df = pd.DataFrame([{"id": c.id, "title": c.title, "description": c.description, "created_at": c.created_at} for c in db2.query(Course).all()])
1529
+ en_df = pd.DataFrame([{"id": e.id, "course_id": e.course_id, "student_name": e.student_name, "student_email": e.student_email, "created_at": e.created_at} for e in db2.query(Enrollment).all()])
1530
+ md_df = pd.DataFrame([{"id": m.id, "course_id": m.course_id, "title": m.title, "description": m.description, "video_path": m.video_path, "created_at": m.created_at} for m in db2.query(Lesson).all()])
1531
+ ag_df = pd.DataFrame([{"id": a.id, "course_id": a.course_id, "class_date": a.class_date, "start_time": a.start_time, "end_time": a.end_time, "topic": a.topic, "created_at": a.created_at} for a in db2.query(Schedule).all()])
1532
+ grades_df = pd.DataFrame([{
1533
+ "id": g.id, "course_id": g.course_id, "student_name": g.student_name,
1534
+ "student_email": g.student_email, "grade": g.grade, "note": g.note, "created_at": g.created_at
1535
+ } for g in db2.query(Grade).all()])
1536
+ certs_df = pd.DataFrame([{
1537
+ "id": c.id, "course_id": c.course_id, "student_name": c.student_name,
1538
+ "student_email": c.student_email, "pdf_path": c.pdf_path, "issued_at": c.issued_at
1539
+ } for c in db2.query(Certificate).all()])
1540
+ mk_df = pd.DataFrame([{
1541
+ "id": m.id, "course_id": m.course_id, "student_name": m.student_name,
1542
+ "student_email": m.student_email, "requested_date": m.requested_date,
1543
+ "note": m.note, "status": m.status, "created_at": m.created_at
1544
+ } for m in db2.query(MakeupRequest).all()])
1545
+ finally:
1546
+ db2.close()
1547
+
1548
+ # Garantir auxiliares antes do snapshot CSV (para SELECT funcionar bem no SQLite)
1549
+ ensure_presence_table()
1550
+ ensure_video_access_tables()
1551
+ ensure_comments_table()
1552
+
1553
+ def _safe_read_sql(query: str, conn: sqlite3.Connection) -> pd.DataFrame:
1554
+ try:
1555
+ return pd.read_sql_query(query, conn)
1556
+ except Exception:
1557
+ q = query.lower()
1558
+ if "from student_auth" in q:
1559
+ return pd.DataFrame(columns=["student_email", "password_hash", "created_at"])
1560
+ if "from video_access_list" in q:
1561
+ return pd.DataFrame(columns=["lesson_id", "student_email", "created_at"])
1562
+ if "from video_access" in q:
1563
+ return pd.DataFrame(columns=["lesson_id", "visibility", "updated_at"])
1564
+ if "from presence" in q:
1565
+ return pd.DataFrame(columns=["session_id","user_email","user_name","role","page","first_seen","last_seen"])
1566
+ if "from comments" in q:
1567
+ return pd.DataFrame(columns=["id","course_id","student_email","student_name","content","parent_id","created_at"])
1568
+ return pd.DataFrame()
1569
+
1570
+ with sqlite3.connect(DB_PATH) as _conn:
1571
+ try:
1572
+ student_auth_df = _safe_read_sql("SELECT student_email, password_hash, created_at FROM student_auth", _conn)
1573
+ except Exception:
1574
+ student_auth_df = pd.DataFrame()
1575
+ video_access_df = _safe_read_sql("SELECT lesson_id, visibility, updated_at FROM video_access", _conn)
1576
+ video_acl_df = _safe_read_sql("SELECT lesson_id, student_email, created_at FROM video_access_list", _conn)
1577
+ presence_df = _safe_read_sql("SELECT session_id, user_email, user_name, role, page, first_seen, last_seen FROM presence", _conn)
1578
+ comments_df = _safe_read_sql("SELECT id, course_id, student_email, student_name, content, parent_id, created_at FROM comments", _conn)
1579
+
1580
+ colb1, colb2, colb3 = st.columns(3)
1581
+ colb1.download_button("⬇️ CSV — Cursos", data=cur_df.to_csv(index=False).encode("utf-8-sig"), file_name="courses.csv")
1582
+ colb1.download_button("⬇️ CSV — Alunos", data=en_df.to_csv(index=False).encode("utf-8-sig"), file_name="enrollments.csv")
1583
+ colb1.download_button("⬇️ CSV — Módulos", data=md_df.to_csv(index=False).encode("utf-8-sig"), file_name="lessons.csv")
1584
+
1585
+ colb2.download_button("⬇️ CSV — Agenda", data=ag_df.to_csv(index=False).encode("utf-8-sig"), file_name="schedule.csv")
1586
+ colb2.download_button("⬇️ CSV — Notas", data=grades_df.to_csv(index=False).encode("utf-8-sig"), file_name="grades.csv")
1587
+ colb2.download_button("⬇️ CSV — Certificados", data=certs_df.to_csv(index=False).encode("utf-8-sig"), file_name="certificates.csv")
1588
+
1589
+ colb3.download_button("⬇️ CSV — Reposições", data=mk_df.to_csv(index=False).encode("utf-8-sig"), file_name="makeup_requests.csv")
1590
+ colb3.download_button("⬇️ CSV — Vídeo: visibilidade", data=video_access_df.to_csv(index=False).encode("utf-8-sig"), file_name="video_access.csv")
1591
+ colb3.download_button("⬇️ CSV — Vídeo: ACL", data=video_acl_df.to_csv(index=False).encode("utf-8-sig"), file_name="video_access_list.csv")
1592
+ st.download_button("⬇️ CSV — Comentários", data=comments_df.to_csv(index=False).encode("utf-8-sig"), file_name="comments.csv")
1593
+ st.download_button("⬇️ CSV — Presença (snapshot)", data=presence_df.to_csv(index=False).encode("utf-8-sig"), file_name="presence.csv")
1594
+
1595
+ st.markdown("---")
1596
+ st.subheader("🧨 Reset da Base (Atenção: ação irreversível)")
1597
+ st.warning("Isto apaga TODOS os dados do banco (cursos, módulos, apostilas, agenda, matrículas, notas, certificados, reposições e auxiliares). Não apaga arquivos em 'data/'.")
1598
+ confirm = st.text_input("Confirmação", placeholder="APAGAR TUDO")
1599
+ btn = st.button("Apagar tudo agora", type="primary", disabled=(confirm.strip().upper() != "APAGAR TUDO"))
1600
+ if btn:
1601
+ ok, err = reset_database(db)
1602
+ if ok:
1603
+ st.success("✅ Base resetada com sucesso (tabelas esvaziadas).")
1604
+ else:
1605
+ st.error(f"Falha ao resetar base: {err}")
1606
+
1607
+ finally:
1608
+ db.close()
aluno.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pages/aluno.py
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ import re
5
+ import json
6
+ from datetime import datetime
7
+ from typing import Optional, Dict, Any, List
8
+
9
+ import pandas as pd
10
+ import streamlit as st
11
+ from sqlalchemy import func
12
+
13
+ # ==========================
14
+ # Imports com fallback (modular → raiz)
15
+ # ==========================
16
+ from models import (
17
+ Course, Lesson, Material, Schedule, Enrollment, Grade, MakeupRequest, Certificate
18
+ )
19
+
20
+ try:
21
+ from core.db_ready import ensure_db_ready, commit_with_retry
22
+ except Exception:
23
+ from db_ready import ensure_db_ready, commit_with_retry
24
+
25
+ try:
26
+ from core.student_auth import has_student_password, check_student_password
27
+ except Exception:
28
+ from student_auth import has_student_password, check_student_password
29
+
30
+ try:
31
+ from core.video_access import is_video_allowed_for_student, get_video_visibility
32
+ except Exception:
33
+ from video_access import is_video_allowed_for_student, get_video_visibility
34
+
35
+ try:
36
+ from core.presence import update_presence
37
+ except Exception:
38
+ from presence import update_presence
39
+
40
+ try:
41
+ from ui.gallery import aba_galeria_relatorios
42
+ except Exception:
43
+ # fallback se gallery.py estiver na raiz
44
+ from gallery import aba_galeria_relatorios
45
+
46
+ try:
47
+ from utils import human_dt
48
+ except Exception:
49
+ # fallback simples, caso utils.human_dt não exista
50
+ def human_dt(dt_obj) -> str:
51
+ try:
52
+ return pd.to_datetime(dt_obj).strftime("%d/%m/%Y %H:%M")
53
+ except Exception:
54
+ return str(dt_obj)
55
+
56
+
57
+ # ==========================
58
+ # Helpers locais
59
+ # ==========================
60
+ def is_url(s: Optional[str]) -> bool:
61
+ s = (s or "").strip().lower()
62
+ return s.startswith("http://") or s.startswith("https://")
63
+
64
+
65
+ def normalize_youtube_url(url: str) -> str:
66
+ """
67
+ Converte variantes (youtu.be, /watch?v=, /embed/, /shorts/) em watch URL canônica:
68
+ https://www.youtube.com/watch?v=VIDEO_ID
69
+ """
70
+ if not url:
71
+ return url
72
+ u = url.strip()
73
+
74
+ m = re.search(r"(?:https?://)?(?:www\.)?youtu\.be/([A-Za-z0-9_-]{6,})", u)
75
+ if m:
76
+ vid = m.group(1)
77
+ return f"https://www.youtube.com/watch?v={vid}"
78
+
79
+ m = re.search(r"(?:https?://)?(?:www\.)?youtube\.com/watch\?v=([A-Za-z0-9_-]{6,})", u)
80
+ if m:
81
+ return f"https://www.youtube.com/watch?v={m.group(1)}"
82
+
83
+ m = re.search(r"(?:https?://)?(?:www\.)?youtube\.com/embed/([A-Za-z0-9_-]{6,})", u)
84
+ if m:
85
+ return f"https://www.youtube.com/watch?v={m.group(1)}"
86
+
87
+ m = re.search(r"(?:https?://)?(?:www\.)?youtube\.com/shorts/([A-Za-z0-9_-]{6,})", u)
88
+ if m:
89
+ return f"https://www.youtube.com/watch?v={m.group(1)}"
90
+
91
+ return u
92
+
93
+
94
+ def parse_schedule_topic(topic_raw: str) -> Dict[str, Any]:
95
+ """
96
+ Interpreta Schedule.topic:
97
+ - JSON com chaves: topic, module_id, assigned_emails, occupancy, module_index
98
+ - Aceita extras: details/descricao, semana, off_schedule, aluno_nome, matricula
99
+ - Texto k:v; ... | texto livre
100
+ """
101
+ defaults = {
102
+ "topic": None,
103
+ "module_id": None,
104
+ "assigned_emails": [],
105
+ "occupancy": "",
106
+ "module_index": None,
107
+ "details": None,
108
+ "descricao": None,
109
+ "semana": None,
110
+ "off_schedule": False,
111
+ "aluno_nome": None,
112
+ "matricula": None,
113
+ }
114
+ if not topic_raw:
115
+ return defaults
116
+ s = (topic_raw or "").strip()
117
+
118
+ # 1) JSON
119
+ try:
120
+ obj = json.loads(s)
121
+ if isinstance(obj, dict):
122
+ out = defaults.copy()
123
+ out["topic"] = obj.get("topic") or obj.get("titulo") or obj.get("assunto") or None
124
+ out["module_id"] = obj.get("module_id") or obj.get("mod_id") or obj.get("lesson_id") or None
125
+ emails = obj.get("assigned_emails") or obj.get("emails") or []
126
+ if isinstance(emails, str):
127
+ emails = [e.strip().lower() for e in emails.split(",") if e.strip()]
128
+ elif isinstance(emails, list):
129
+ emails = [(e or "").strip().lower() for e in emails if (e or "").strip()]
130
+ else:
131
+ emails = []
132
+ out["assigned_emails"] = emails
133
+ out["occupancy"] = (obj.get("occupancy") or obj.get("ocupacao") or "").strip()
134
+ out["module_index"] = obj.get("module_index") or obj.get("indice") or None
135
+ # extras
136
+ out["details"] = obj.get("details")
137
+ out["descricao"] = obj.get("descricao")
138
+ out["semana"] = obj.get("semana")
139
+ out["off_schedule"] = bool(obj.get("off_schedule", False))
140
+ out["aluno_nome"] = obj.get("aluno_nome")
141
+ out["matricula"] = obj.get("matricula")
142
+ return out
143
+ except Exception:
144
+ pass
145
+
146
+ # 2) "k: v; k: v"
147
+ try:
148
+ parts = [p.strip() for p in re.split(r"[;|]\s*", s) if p.strip()]
149
+ kv = {}
150
+ for p in parts:
151
+ if ":" in p:
152
+ k, v = p.split(":", 1)
153
+ kv[k.strip().lower()] = v.strip()
154
+ if kv:
155
+ out = defaults.copy()
156
+ out["topic"] = kv.get("topic") or kv.get("assunto") or None
157
+ mid = kv.get("module_id")
158
+ out["module_id"] = int(mid) if (mid and str(mid).isdigit()) else None
159
+ emails = kv.get("assigned_emails") or kv.get("emails") or ""
160
+ out["assigned_emails"] = [e.strip().lower() for e in emails.split(",") if e.strip()]
161
+ out["occupancy"] = kv.get("occupancy") or kv.get("ocupacao") or ""
162
+ out["module_index"] = kv.get("module_index") or kv.get("indice") or None
163
+ # extras
164
+ out["details"] = kv.get("details") or kv.get("descricao")
165
+ out["descricao"] = kv.get("descricao")
166
+ out["semana"] = kv.get("semana")
167
+ out["off_schedule"] = str(kv.get("off_schedule", "")).strip().lower() in ("1", "true", "sim", "yes")
168
+ out["aluno_nome"] = kv.get("aluno_nome")
169
+ out["matricula"] = kv.get("matricula")
170
+ return out
171
+ except Exception:
172
+ pass
173
+
174
+ # 3) Texto puro
175
+ out = defaults.copy()
176
+ out["topic"] = s
177
+ return out
178
+
179
+
180
+ # ==========================================================
181
+ # Login do aluno
182
+ # ==========================================================
183
+ def aluno_login_ui() -> None:
184
+ if st.session_state.aluno_logged_in:
185
+ with st.container():
186
+ st.success(f"Conectado como {st.session_state.aluno_nome or st.session_state.aluno_email}")
187
+ if st.button("Sair (aluno)", key="btn_aluno_logout"):
188
+ st.session_state.aluno_logged_in = False
189
+ st.session_state.aluno_nome = ""
190
+ st.session_state.aluno_email = ""
191
+ st.rerun()
192
+ return
193
+
194
+ st.markdown("### 🙋 Acesso do Aluno")
195
+ with st.form("aluno_login", clear_on_submit=False):
196
+ email = st.text_input("E-mail", value="", placeholder="seuemail@exemplo.com").strip().lower()
197
+ senha = st.text_input("Senha", type="password", value="")
198
+ ok = st.form_submit_button("Entrar", type="primary")
199
+ if ok:
200
+ if not email or not senha:
201
+ st.error("Informe e-mail e senha.")
202
+ return
203
+ db = ensure_db_ready()
204
+ try:
205
+ en = db.query(Enrollment).filter(Enrollment.student_email == email).first()
206
+ if not en:
207
+ st.error("E-mail não cadastrado como aluno.")
208
+ return
209
+ finally:
210
+ db.close()
211
+ if not has_student_password(email):
212
+ st.error("Senha não definida. Solicite ao administrador definir uma senha para você.")
213
+ return
214
+ if not check_student_password(email, senha):
215
+ st.error("Senha incorreta.")
216
+ return
217
+ st.session_state.aluno_logged_in = True
218
+ st.session_state.aluno_email = email
219
+ st.session_state.aluno_nome = en.student_name if en and en.student_name else ""
220
+ st.success("Login realizado.")
221
+ st.rerun()
222
+
223
+
224
+ def _aluno_presence_ping(page_label: str):
225
+ role = "aluno" if st.session_state.get("aluno_logged_in") else "visitante"
226
+ email = st.session_state.get("aluno_email") if st.session_state.get("aluno_logged_in") else None
227
+ nome = st.session_state.get("aluno_nome") if st.session_state.get("aluno_logged_in") else None
228
+ update_presence(role=role, page=page_label, user_email=email, user_name=nome)
229
+
230
+
231
+ # ==========================================================
232
+ # View do aluno
233
+ # ==========================================================
234
+ def render() -> None:
235
+ _aluno_presence_ping(page_label="aluno_home")
236
+
237
+ st.header("🎓 Portal do Aluno — Pega a Visão")
238
+ aluno_login_ui()
239
+ if not st.session_state.aluno_logged_in:
240
+ st.info("Faça login para acessar seu conteúdo.")
241
+ return
242
+
243
+ db = ensure_db_ready()
244
+ try:
245
+ courses = db.query(Course).order_by(Course.title.asc()).all()
246
+ if not courses:
247
+ st.info("Nenhum curso cadastrado ainda.")
248
+ return
249
+
250
+ c1, c2 = st.columns([2, 1])
251
+ with c1:
252
+ idx = st.selectbox(
253
+ "Selecione um curso",
254
+ options=list(range(len(courses))),
255
+ format_func=lambda i: courses[i].title
256
+ )
257
+ curso: Course = courses[idx]
258
+ st.subheader(f"📘 {curso.title}")
259
+ st.write(curso.description or "—")
260
+ with c2:
261
+ st.markdown("**Resumo do Curso**")
262
+ st.metric("Módulos", db.query(func.count(Lesson.id)).filter(Lesson.course_id == curso.id).scalar() or 0)
263
+ st.metric("PDFs", db.query(func.count(Material.id)).filter(Material.course_id == curso.id).scalar() or 0)
264
+ st.metric("Dias de aula", db.query(func.count(Schedule.id)).filter(Schedule.course_id == curso.id).scalar() or 0)
265
+ st.metric("Matriculados", db.query(func.count(Enrollment.id)).filter(Enrollment.course_id == curso.id).scalar() or 0)
266
+
267
+ st.divider()
268
+ tab_turma, tab_mods, tab_pdfs, tab_crono, tab_reposicao, tab_cert, tab_coment, tab_galeria = st.tabs([
269
+ "Turma em andamento", "Módulos (vídeo)", "Apostilas (PDF)", "Meu cronograma", "Reposição",
270
+ "Certificado", "Comentários", "Galeria de Relatórios"
271
+ ])
272
+
273
+ # -------- Turma em andamento --------
274
+ with tab_turma:
275
+ try:
276
+ agenda = (
277
+ db.query(Schedule)
278
+ .filter(Schedule.course_id == curso.id)
279
+ .order_by(Schedule.class_date.asc(), Schedule.start_time.asc())
280
+ .all()
281
+ )
282
+ lessons_by_id = {
283
+ m.id: m
284
+ for m in db.query(Lesson).filter(Lesson.course_id == curso.id).all()
285
+ }
286
+ rows = []
287
+ for a in agenda:
288
+ meta = parse_schedule_topic(a.topic)
289
+ mod = lessons_by_id.get(meta.get("module_id")) if meta.get("module_id") else None
290
+ assigned = set((meta.get("assigned_emails") or []))
291
+ occupancy = (meta.get("occupancy") or "").strip()
292
+ show_full = (not assigned) or (st.session_state.aluno_email in assigned)
293
+ if show_full:
294
+ aula_label = mod.title if mod else (meta.get("topic") or "—")
295
+ else:
296
+ aula_label = "AO VIVO" if occupancy.upper() == "AO VIVO" else "Aula agendada"
297
+ rows.append({
298
+ "Data": a.class_date,
299
+ "Início": a.start_time.strftime("%H:%M") if a.start_time else "",
300
+ "Fim": a.end_time.strftime("%H:%M") if a.end_time else "",
301
+ "Aula": aula_label,
302
+ })
303
+ if rows:
304
+ st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)
305
+ else:
306
+ st.info("Sem agenda cadastrada.")
307
+ except Exception as e:
308
+ st.error("Falha ao renderizar 'Turma em andamento'.")
309
+ st.exception(e)
310
+
311
+ # -------- Módulos (vídeo) --------
312
+ with tab_mods:
313
+ try:
314
+ lessons = (
315
+ db.query(Lesson)
316
+ .filter(Lesson.course_id == curso.id)
317
+ .order_by(Lesson.created_at.asc())
318
+ .all()
319
+ )
320
+ if not lessons:
321
+ st.info("Sem módulos cadastrados.")
322
+ else:
323
+ for les in lessons:
324
+ with st.expander(f"🎬 {les.title}", expanded=False):
325
+ if les.description:
326
+ st.caption(les.description)
327
+
328
+ has_video = bool(les.video_path and (is_url(les.video_path) or os.path.exists(les.video_path)))
329
+ if not has_video:
330
+ st.warning("Vídeo indisponível.")
331
+ else:
332
+ allowed = is_video_allowed_for_student(
333
+ lesson_id=les.id,
334
+ student_email=st.session_state.aluno_email,
335
+ is_admin=False
336
+ )
337
+ if allowed:
338
+ if is_url(les.video_path):
339
+ st.video(les.video_path)
340
+ st.caption("Fonte: YouTube")
341
+ else:
342
+ st.video(les.video_path)
343
+ st.caption("Fonte: arquivo local")
344
+ vis = get_video_visibility(les.id)
345
+ if vis == "restricted":
346
+ st.caption("Acesso: restrito (você está autorizado).")
347
+ else:
348
+ st.caption("Acesso: público.")
349
+ else:
350
+ vis = get_video_visibility(les.id)
351
+ if vis == "private":
352
+ st.error("Este vídeo é privado. Somente administradores podem assistir.")
353
+ elif vis == "restricted":
354
+ st.warning("Você não tem permissão para assistir este vídeo.")
355
+ else:
356
+ st.warning("Você não tem permissão para assistir este vídeo.")
357
+ except Exception as e:
358
+ st.error("Falha ao renderizar 'Módulos (vídeo)'.")
359
+ st.exception(e)
360
+
361
+ # -------- Apostilas (PDF) --------
362
+ with tab_pdfs:
363
+ try:
364
+ mats = (
365
+ db.query(Material)
366
+ .filter(Material.course_id == curso.id)
367
+ .order_by(Material.created_at.asc())
368
+ .all()
369
+ )
370
+ if not mats:
371
+ st.info("Sem apostilas cadastradas.")
372
+ else:
373
+ for m in mats:
374
+ col_left, col_right = st.columns([3, 1])
375
+ col_left.write(f"📄 **{m.title}**")
376
+ if m.pdf_path and os.path.exists(m.pdf_path):
377
+ try:
378
+ with open(m.pdf_path, "rb") as f:
379
+ col_right.download_button(
380
+ "Baixar PDF",
381
+ data=f.read(),
382
+ file_name=os.path.basename(m.pdf_path),
383
+ key=f"dl_pdf_{m.id}"
384
+ )
385
+ except Exception:
386
+ col_right.warning("Falha ao abrir o arquivo do PDF.")
387
+ else:
388
+ col_right.warning("Arquivo não encontrado.")
389
+ except Exception as e:
390
+ st.error("Falha ao renderizar 'Apostilas'.")
391
+ st.exception(e)
392
+
393
+ # -------- Meu cronograma --------
394
+ with tab_crono:
395
+ try:
396
+ st.subheader("🗓️ Meu cronograma")
397
+ agenda = (
398
+ db.query(Schedule)
399
+ .filter(Schedule.course_id == curso.id)
400
+ .order_by(Schedule.class_date.asc(), Schedule.start_time.asc())
401
+ .all()
402
+ )
403
+ lessons_by_id = {
404
+ m.id: m
405
+ for m in db.query(Lesson).filter(Lesson.course_id == curso.id).all()
406
+ }
407
+ linhas = []
408
+ for a in agenda:
409
+ meta = parse_schedule_topic(a.topic)
410
+ mod = lessons_by_id.get(meta.get("module_id")) if meta.get("module_id") else None
411
+ assigned = set((meta.get("assigned_emails") or []))
412
+ occupancy = (meta.get("occupancy") or "").strip()
413
+ show_full = (not assigned) or (st.session_state.aluno_email in assigned)
414
+ label = (mod.title if mod else meta.get("topic") or "—") if show_full else (
415
+ "AO VIVO" if occupancy.upper() == "AO VIVO" else "Aula agendada"
416
+ )
417
+ linhas.append({
418
+ "Data": a.class_date,
419
+ "Início": a.start_time.strftime("%H:%M") if a.start_time else "",
420
+ "Fim": a.end_time.strftime("%H:%M") if a.end_time else "",
421
+ "Módulo/Aula": label,
422
+ })
423
+ if linhas:
424
+ st.dataframe(pd.DataFrame(linhas), use_container_width=True, hide_index=True)
425
+ else:
426
+ st.info("Sem itens de cronograma para você no momento.")
427
+ except Exception as e:
428
+ st.error("Falha ao renderizar 'Meu cronograma'.")
429
+ st.exception(e)
430
+
431
+ # -------- Reposição --------
432
+ with tab_reposicao:
433
+ try:
434
+ st.subheader("Solicitar aula de reposição")
435
+ with st.form("reposicao_form", clear_on_submit=True):
436
+ nome = st.text_input("Seu nome completo", value=st.session_state.aluno_nome or "")
437
+ email = st.text_input("Seu e-mail", value=st.session_state.aluno_email or "", disabled=True)
438
+ data_desejada = st.date_input("Data desejada")
439
+ observ = st.text_area("Observações (opcional)")
440
+ ok = st.form_submit_button("Solicitar")
441
+ if ok:
442
+ if not nome or not st.session_state.aluno_email:
443
+ st.error("Preencha nome e esteja logado.")
444
+ else:
445
+ req = MakeupRequest(
446
+ course_id=curso.id,
447
+ student_name=nome.strip(),
448
+ student_email=st.session_state.aluno_email,
449
+ requested_date=data_desejada,
450
+ note=observ.strip() if observ else None,
451
+ status="pending"
452
+ )
453
+ db.add(req)
454
+ commit_with_retry(db)
455
+ st.success("Solicitação enviada. Você será notificado por e-mail (fora do app) quando houver confirmação.")
456
+ except Exception as e:
457
+ st.error("Falha ao renderizar 'Reposição'.")
458
+ st.exception(e)
459
+
460
+ # -------- Certificado --------
461
+ with tab_cert:
462
+ try:
463
+ st.subheader("Baixar certificado de conclusão")
464
+ st.caption("Disponível somente para alunos matriculados com certificado emitido pelo Admin.")
465
+ nome = st.text_input("Nome completo", value=st.session_state.aluno_nome or "", key="cert_nome_aluno")
466
+ email = st.text_input("E-mail", value=st.session_state.aluno_email, disabled=True, key="cert_email_aluno_display")
467
+
468
+ db_cert = ensure_db_ready()
469
+ try:
470
+ if st.button("Verificar e baixar", key="btn_cert_aluno"):
471
+ enrolled = (
472
+ db_cert.query(Enrollment)
473
+ .filter(Enrollment.course_id == curso.id, Enrollment.student_email == st.session_state.aluno_email)
474
+ .first()
475
+ )
476
+ if not enrolled:
477
+ st.error("Este e-mail não está matriculado neste curso.")
478
+ else:
479
+ cert = (
480
+ db_cert.query(Certificate)
481
+ .filter(Certificate.course_id == curso.id, Certificate.student_email == st.session_state.aluno_email)
482
+ .order_by(Certificate.issued_at.desc())
483
+ .first()
484
+ )
485
+ if not cert:
486
+ st.warning("Nenhum certificado emitido ainda para este aluno.")
487
+ else:
488
+ if cert.pdf_path and os.path.exists(cert.pdf_path):
489
+ with open(cert.pdf_path, "rb") as f:
490
+ st.download_button(
491
+ "⬇️ Baixar certificado (PDF)",
492
+ data=f.read(),
493
+ file_name=os.path.basename(cert.pdf_path),
494
+ key=f"dl_cert_{cert.id}"
495
+ )
496
+ else:
497
+ st.error("Arquivo do certificado não encontrado.")
498
+ finally:
499
+ db_cert.close()
500
+ except Exception as e:
501
+ st.error("Falha ao renderizar 'Certificado'.")
502
+ st.exception(e)
503
+
504
+ # -------- Comentários --------
505
+ with tab_coment:
506
+ try:
507
+ st.subheader("💬 Comentários do curso")
508
+ from core.comments import add_comment, get_comments as _get_comments # preferencial
509
+ except Exception:
510
+ from comments import add_comment, get_comments as _get_comments # fallback
511
+
512
+ try:
513
+ with st.form(f"comment_form_{curso.id}", clear_on_submit=True):
514
+ txt = st.text_area("Escreva seu comentário", height=120, placeholder="Respeite as diretrizes da comunidade…")
515
+ okc = st.form_submit_button("Publicar comentário", type="primary")
516
+ if okc:
517
+ try:
518
+ add_comment(
519
+ course_id=curso.id,
520
+ student_email=st.session_state.aluno_email,
521
+ student_name=st.session_state.aluno_nome or st.session_state.aluno_email,
522
+ content=txt,
523
+ parent_id=None
524
+ )
525
+ st.success("Comentário publicado.")
526
+ st.rerun()
527
+ except Exception as e:
528
+ st.error(f"Não foi possível publicar: {e}")
529
+
530
+ dfc = _get_comments(curso.id)
531
+ if dfc is None or dfc.empty:
532
+ st.info("Ainda não há comentários para este curso. Seja o primeiro!")
533
+ else:
534
+ # Thread simples (1 nível de resposta)
535
+ roots = dfc[dfc['parent_id'].isna()].copy()
536
+ replies = dfc[~dfc['parent_id'].isna()].copy()
537
+ replies_by_parent = {}
538
+ for _, r in replies.iterrows():
539
+ replies_by_parent.setdefault(int(r['parent_id']), []).append(r)
540
+
541
+ for _, r in roots.iterrows():
542
+ st.markdown(
543
+ f"**{r['student_name'] or r['student_email']}** · _{human_dt(pd.to_datetime(r['created_at']))}_\n{r['content']}"
544
+ )
545
+ with st.expander("Responder", expanded=False):
546
+ with st.form(f"reply_{r['id']}", clear_on_submit=True):
547
+ txtr = st.text_area("Sua resposta", key=f"txtr_{r['id']}")
548
+ okr = st.form_submit_button("Responder")
549
+ if okr:
550
+ try:
551
+ add_comment(
552
+ course_id=curso.id,
553
+ student_email=st.session_state.aluno_email,
554
+ student_name=st.session_state.aluno_nome or st.session_state.aluno_email,
555
+ content=txtr,
556
+ parent_id=int(r['id'])
557
+ )
558
+ st.success("Resposta publicada.")
559
+ st.rerun()
560
+ except Exception as e:
561
+ st.error(f"Não foi possível publicar a resposta: {e}")
562
+
563
+ # Render replies (1 nível)
564
+ for rr in replies_by_parent.get(int(r['id']), []):
565
+ st.markdown(
566
+ f"\n> **{rr['student_name'] or rr['student_email']}** · _{human_dt(pd.to_datetime(rr['created_at']))}_\n> {rr['content']}"
567
+ )
568
+ except Exception as e:
569
+ st.error("Falha ao renderizar 'Comentários'.")
570
+ st.exception(e)
571
+
572
+ # -------- Galeria de Relatórios --------
573
+ with tab_galeria:
574
+ try:
575
+ aba_galeria_relatorios(context_key="aluno_")
576
+ except Exception as e:
577
+ st.error("Falha ao renderizar 'Galeria de Relatórios'.")
578
+ st.exception(e)
579
+
580
+ finally:
581
+ db.close()
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ import sys
5
+ import streamlit as st
6
+
7
+ # --- Garante que a raiz do projeto está no sys.path (prioriza seus módulos locais) ---
8
+ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
9
+ if PROJECT_ROOT not in sys.path:
10
+ sys.path.insert(0, PROJECT_ROOT)
11
+
12
+ # --- Imports de config (compatível com sua pasta 'Config' MAIÚSCULA; fallback para 'config') ---
13
+ try:
14
+ from Config.settings import APP_TITLE, APP_ICON, APP_LAYOUT
15
+ except ModuleNotFoundError:
16
+ # fallback se renomear a pasta para 'config' no futuro
17
+ from config.settings import APP_TITLE, APP_ICON, APP_LAYOUT
18
+
19
+ # --- Utilidades base do projeto ---
20
+ from utils import ensure_dirs
21
+
22
+ # --- Banco de dados (módulo local 'db.py' que criamos) ---
23
+ from db import init_db
24
+
25
+ # --- Páginas (na RAIZ, conforme sua estrutura) ---
26
+ import aluno as page_aluno
27
+ import admin as page_admin
28
+
29
+
30
+ # ==========================
31
+ # Boot do App
32
+ # ==========================
33
+ st.set_page_config(page_title=APP_TITLE, page_icon=APP_ICON, layout=APP_LAYOUT)
34
+ ensure_dirs()
35
+ init_db()
36
+
37
+ # Estados padrão
38
+ st.session_state.setdefault("is_admin", False)
39
+ st.session_state.setdefault("admin_user", None)
40
+ st.session_state.setdefault("aluno_logged_in", False)
41
+ st.session_state.setdefault("aluno_nome", "")
42
+ st.session_state.setdefault("aluno_email", "")
43
+ st.session_state.setdefault("cal_ver", 0)
44
+
45
+
46
+ # ==========================
47
+ # Router
48
+ # ==========================
49
+ def main() -> None:
50
+ st.title(APP_TITLE)
51
+ tab_aluno, tab_admin = st.tabs(["👩‍🎓 Aluno", "🛠️ Admin"])
52
+
53
+ with tab_aluno:
54
+ try:
55
+ page_aluno.render()
56
+ except Exception as e:
57
+ st.error("Ocorreu um erro ao carregar a aba **Aluno**. Os demais menus continuam disponíveis.")
58
+ st.exception(e)
59
+
60
+ with tab_admin:
61
+ try:
62
+ page_admin.render()
63
+ except Exception as e:
64
+ st.error("Ocorreu um erro ao carregar a aba **Admin**.")
65
+ st.exception(e)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
app_config.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # config/settings.py
2
+ from pathlib import Path
3
+ import os
4
+ import hashlib
5
+
6
+ APP_TITLE = "Academia de Cursos — Pega a Visão"
7
+ APP_ICON = "🎓"
8
+ APP_LAYOUT = "wide"
9
+
10
+ BASE_DIR = Path(__file__).resolve().parents[1]
11
+ DATA_DIR = BASE_DIR / "data"
12
+
13
+ # ======= Galeria =======
14
+ GALLERY_DIR = DATA_DIR / "reports_photos"
15
+ THUMB_DIR = GALLERY_DIR / "_thumbs"
16
+ GALLERY_ALLOWED_EXT = {".png", ".jpg", ".jpeg", ".webp"}
17
+ THUMB_MAX = (512, 512)
18
+ PAGE_SIZE_DEFAULT = 12
19
+
20
+ # ======= Backup =======
21
+ AUTO_BKP_INTERVAL_SEC = 10 * 60 # 10 min
22
+
23
+ # ======= Admin Auth =======
24
+ # A senha fixa de admin no seu app é "21003887" (hash abaixo). Deixe assim para compatibilidade.
25
+ ADMIN_FIXED_PASS_HASH = hashlib.sha256("21003887".encode()).hexdigest()
backup_hf.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/backup_hf.py
2
+ import os, io, zipfile, hashlib
3
+ from datetime import datetime
4
+ from typing import Dict, Any
5
+ from db import DB_PATH
6
+
7
+ HF_HUB_AVAILABLE = True
8
+ try:
9
+ from huggingface_hub import HfApi, upload_file
10
+ except Exception:
11
+ HF_HUB_AVAILABLE = False
12
+
13
+ def _file_md5(path: str, chunk_size: int = 1024 * 1024) -> str:
14
+ md5 = hashlib.md5()
15
+ with open(path, "rb") as f:
16
+ while True:
17
+ chunk = f.read(chunk_size)
18
+ if not chunk: break
19
+ md5.update(chunk)
20
+ return md5.hexdigest()
21
+
22
+ def _dir_fingerprint(dir_path: str) -> str:
23
+ parts = []
24
+ if not os.path.isdir(dir_path): return ""
25
+ for root, _, files in os.walk(dir_path):
26
+ for fn in sorted(files):
27
+ full = os.path.join(root, fn)
28
+ try:
29
+ stt = os.stat(full)
30
+ rel = os.path.relpath(full, start=dir_path)
31
+ parts.append(f"{rel}|{stt.st_size}|{int(stt.st_mtime)}")
32
+ except Exception:
33
+ continue
34
+ data = "\n".join(parts).encode("utf-8", errors="ignore")
35
+ return hashlib.md5(data).hexdigest()
36
+
37
+ def _zip_dir_to_bytes(dir_path: str) -> bytes:
38
+ buf = io.BytesIO()
39
+ with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
40
+ if os.path.isdir(dir_path):
41
+ base_root = os.path.dirname(dir_path.rstrip(os.sep)) or "."
42
+ for root, _, files in os.walk(dir_path):
43
+ for f in files:
44
+ full = os.path.join(root, f)
45
+ arc = os.path.relpath(full, start=base_root)
46
+ zf.write(full, arcname=arc)
47
+ buf.seek(0)
48
+ return buf.read()
49
+
50
+ def _sanitize_repo_id(text: str) -> str:
51
+ import re
52
+ s = (text or "").strip()
53
+ if not s: return s
54
+ if "/" in s and not s.startswith("http"):
55
+ return s
56
+ m = re.search(r"huggingface\.co/(?:datasets|models|spaces)/([^/]+)/([^/?#]+)", s, flags=re.I)
57
+ if m:
58
+ return f"{m.group(1)}/{m.group(2)}"
59
+ s = re.sub(r"^https?://", "", s, flags=re.I)
60
+ s = s.strip("/")
61
+ if "/" in s:
62
+ return "/".join(s.split("/")[-2:])
63
+ return s
64
+
65
+ def sync_to_hf_dataset(dataset_repo: str, db_path: str = DB_PATH, data_dir: str = "data") -> Dict[str, Any]:
66
+ if not HF_HUB_AVAILABLE:
67
+ raise RuntimeError("huggingface_hub indisponível.")
68
+ token = os.environ.get("HF_TOKEN") or ""
69
+ if not token.strip():
70
+ raise RuntimeError("HF_TOKEN ausente.")
71
+
72
+ api = HfApi(token=token)
73
+ results = {"db_uploaded": False, "data_uploaded": False}
74
+
75
+ if db_path and os.path.exists(db_path):
76
+ upload_file(
77
+ path_or_fileobj=db_path,
78
+ path_in_repo="db.sqlite",
79
+ repo_id=dataset_repo, repo_type="dataset", token=token,
80
+ commit_message=f"Backup db.sqlite ({datetime.utcnow().isoformat()}Z)"
81
+ )
82
+ results["db_uploaded"] = True
83
+
84
+ if data_dir and os.path.isdir(data_dir):
85
+ zip_bytes = _zip_dir_to_bytes(data_dir)
86
+ upload_file(
87
+ path_or_fileobj=io.BytesIO(zip_bytes),
88
+ path_in_repo="data.zip",
89
+ repo_id=dataset_repo, repo_type="dataset", token=token,
90
+ commit_message=f"Backup data/ (ZIP) ({datetime.utcnow().isoformat()}Z)"
91
+ )
92
+ results["data_uploaded"] = True
93
+
94
+ return results
95
+
96
+ def auto_backup_tick(repo_id: str) -> str:
97
+ import streamlit as st
98
+ if not HF_HUB_AVAILABLE:
99
+ return "huggingface_hub indisponível"
100
+ token_ok = bool((os.environ.get("HF_TOKEN") or "").strip())
101
+ if not token_ok:
102
+ return "HF_TOKEN ausente"
103
+
104
+ repo = _sanitize_repo_id(repo_id)
105
+ if not repo or "/" not in repo:
106
+ return "Repo inválido"
107
+
108
+ db_hash_now = _file_md5(DB_PATH) if os.path.exists(DB_PATH) else ""
109
+ data_fp_now = _dir_fingerprint("data")
110
+
111
+ last_db = st.session_state.get("auto_bkp_last_db_hash", "")
112
+ last_data = st.session_state.get("auto_bkp_last_data_fp", "")
113
+
114
+ to_send = {"db": db_hash_now and (db_hash_now != last_db),
115
+ "data": (data_fp_now != last_data) and bool(data_fp_now)}
116
+
117
+ sent = []
118
+ if to_send["db"] or to_send["data"]:
119
+ stats = sync_to_hf_dataset(dataset_repo=repo, db_path=DB_PATH, data_dir="data")
120
+ if stats.get("db_uploaded"):
121
+ st.session_state["auto_bkp_last_db_hash"] = db_hash_now
122
+ sent.append("db.sqlite")
123
+ if stats.get("data_uploaded"):
124
+ st.session_state["auto_bkp_last_data_fp"] = data_fp_now
125
+ sent.append("data.zip")
126
+ return ", ".join(sent) if sent else "sem mudanças"
comments.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/comments.py
2
+ import os
3
+ import sqlite3
4
+ import pandas as pd
5
+ from typing import Optional
6
+ from db import DB_PATH
7
+
8
+ def _ensure_comments_table() -> None:
9
+ os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
10
+ with sqlite3.connect(DB_PATH) as conn:
11
+ c = conn.cursor()
12
+ c.execute(
13
+ """
14
+ CREATE TABLE IF NOT EXISTS comments (
15
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
16
+ course_id INTEGER NOT NULL,
17
+ student_email TEXT NOT NULL,
18
+ student_name TEXT,
19
+ content TEXT NOT NULL,
20
+ parent_id INTEGER,
21
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
22
+ )
23
+ """
24
+ )
25
+ conn.commit()
26
+
27
+ def add_comment(course_id: int, student_email: str, student_name: str, content: str, parent_id: Optional[int] = None) -> None:
28
+ _ensure_comments_table()
29
+ content = (content or "").strip()
30
+ if not content:
31
+ raise ValueError("Comentário vazio.")
32
+ with sqlite3.connect(DB_PATH) as conn:
33
+ c = conn.cursor()
34
+ c.execute(
35
+ "INSERT INTO comments (course_id, student_email, student_name, content, parent_id) VALUES (?, ?, ?, ?, ?)",
36
+ (course_id, student_email.strip().lower(), (student_name or "").strip(), content, parent_id)
37
+ )
38
+ conn.commit()
39
+
40
+ def delete_comment(comment_id: int) -> None:
41
+ _ensure_comments_table()
42
+ with sqlite3.connect(DB_PATH) as conn:
43
+ c = conn.cursor()
44
+ c.execute("DELETE FROM comments WHERE parent_id=?", (comment_id,))
45
+ c.execute("DELETE FROM comments WHERE id=?", (comment_id,))
46
+ conn.commit()
47
+
48
+ def get_comments(course_id: int) -> pd.DataFrame:
49
+ _ensure_comments_table()
50
+ with sqlite3.connect(DB_PATH) as conn:
51
+ df = pd.read_sql_query(
52
+ "SELECT id, course_id, student_email, student_name, content, parent_id, created_at FROM comments WHERE course_id=? ORDER BY created_at ASC",
53
+ conn,
54
+ params=(course_id,)
55
+ )
56
+ return df
db.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # db.py
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ from pathlib import Path
5
+ from sqlalchemy import create_engine
6
+ from sqlalchemy.orm import sessionmaker
7
+ from typing import Optional
8
+
9
+ # Importa a Base (declarative_base) do seu models.py
10
+ # models.py deve definir: Base = declarative_base()
11
+ from models import Base
12
+
13
+ # Caminho do banco SQLite
14
+ BASE_DIR = Path(__file__).resolve().parent
15
+ DATA_DIR = BASE_DIR / "data"
16
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
17
+
18
+ DB_PATH = str(DATA_DIR / "db.sqlite")
19
+
20
+ # Cria o engine e a fábrica de sessões
21
+ engine = create_engine(
22
+ f"sqlite:///{DB_PATH}",
23
+ connect_args={"check_same_thread": False}, # necessário para SQLite + threads do Streamlit
24
+ echo=False,
25
+ pool_pre_ping=True,
26
+ future=True,
27
+ )
28
+
29
+ SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
30
+
31
+ def init_db() -> None:
32
+ """
33
+ Cria as tabelas caso não existam (com base no models.Base).
34
+ Execute isso no boot do app.
35
+ """
36
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
37
+ Base.metadata.create_all(bind=engine)
38
+
39
+ def get_session_safe():
40
+ """
41
+ Retorna uma sessão do SQLAlchemy para uso com 'with' ou try/finally.
42
+ Obs.: Lembre-se de fechar: db.close()
43
+ """
44
+ return SessionLocal()
db_ready.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/db_ready.py
2
+ from sqlalchemy import text
3
+ from sqlalchemy.exc import OperationalError
4
+ from db import init_db, get_session_safe
5
+ from models import Course
6
+
7
+ def ensure_db_ready():
8
+ """
9
+ Garante que o schema exista antes de utilizar a sessão.
10
+ """
11
+ db = get_session_safe()
12
+ try:
13
+ db.execute(text("SELECT 1"))
14
+ try:
15
+ db.query(Course).limit(1).all()
16
+ return db
17
+ except OperationalError:
18
+ db.close()
19
+ init_db()
20
+ db2 = get_session_safe()
21
+ try:
22
+ db2.query(Course).limit(1).all()
23
+ return db2
24
+ except Exception:
25
+ db2.close()
26
+ raise
27
+ except Exception:
28
+ db.close()
29
+ raise
30
+
31
+ def commit_with_retry(db, on_retry_init: bool = True) -> None:
32
+ try:
33
+ db.commit()
34
+ except OperationalError:
35
+ db.rollback()
36
+ if on_retry_init:
37
+ init_db()
38
+ try:
39
+ db.commit()
40
+ return
41
+ except Exception as e2:
42
+ db.rollback()
43
+ raise e2
44
+ raise
gallery.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gallery.py
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ from pathlib import Path
5
+ import streamlit as st
6
+
7
+ # ===== Config: suporta pasta 'Config' (maiúscula) e 'config' (minúscula) =====
8
+ try:
9
+ from Config.settings import PAGE_SIZE_DEFAULT
10
+ except Exception:
11
+ try:
12
+ from config.settings import PAGE_SIZE_DEFAULT
13
+ except Exception:
14
+ PAGE_SIZE_DEFAULT = 12 # fallback seguro
15
+
16
+ # ===== Storage da galeria: tenta 'core.gallery_storage' e, se não houver 'core/', usa raiz =====
17
+ try:
18
+ from core.gallery_storage import (
19
+ save_report_image,
20
+ gallery_list_images_sorted,
21
+ delete_report_image,
22
+ )
23
+ except Exception:
24
+ from gallery_storage import (
25
+ save_report_image,
26
+ gallery_list_images_sorted,
27
+ delete_report_image,
28
+ )
29
+
30
+
31
+ def render_reports_gallery_uploader(key_prefix: str) -> None:
32
+ """Uploader de imagens para a galeria (qualquer usuário)."""
33
+ st.subheader("📤 Publicar foto do relatório")
34
+ st.caption("Envie uma imagem (JPG/PNG/WEBP). Todos os usuários poderão visualizar na galeria.")
35
+
36
+ uploader_name = ""
37
+ uploader_email = ""
38
+ if st.session_state.get("aluno_logged_in"):
39
+ uploader_name = st.session_state.get("aluno_nome") or ""
40
+ uploader_email = st.session_state.get("aluno_email") or ""
41
+ elif st.session_state.get("is_admin"):
42
+ uploader_name = st.session_state.get("admin_user") or ""
43
+
44
+ col_name, _ = st.columns([2, 3])
45
+ name_input = col_name.text_input(
46
+ "Seu nome (opcional)",
47
+ value=uploader_name,
48
+ max_chars=40,
49
+ placeholder="Ex.: Rodrigo",
50
+ key=f"{key_prefix}gallery_name_input",
51
+ )
52
+
53
+ up = st.file_uploader(
54
+ "Selecione a imagem do relatório",
55
+ type=["png", "jpg", "jpeg", "webp"],
56
+ accept_multiple_files=False,
57
+ help="Dica: até ~5MB carrega mais rápido",
58
+ key=f"{key_prefix}gallery_file_uploader",
59
+ )
60
+
61
+ if up:
62
+ try:
63
+ st.image(up, caption="Pré-visualização", use_container_width=True)
64
+ except Exception:
65
+ st.info("Pré-visualização indisponível para este arquivo.")
66
+
67
+ publish_col, _ = st.columns([1, 3])
68
+ if publish_col.button(
69
+ "📌 Publicar",
70
+ type="primary",
71
+ use_container_width=True,
72
+ disabled=(up is None),
73
+ key=f"{key_prefix}gallery_publish_btn",
74
+ ):
75
+ if up is None:
76
+ st.warning("Selecione uma imagem antes de publicar.")
77
+ return
78
+ try:
79
+ saved = save_report_image(
80
+ uploaded_file=up,
81
+ uploader_name=(name_input or None),
82
+ uploader_email=(uploader_email or None),
83
+ )
84
+ if saved:
85
+ st.success("Imagem publicada com sucesso!")
86
+ st.rerun()
87
+ except Exception as e:
88
+ st.error(f"Falha ao salvar imagem: {e}")
89
+
90
+
91
+ def render_reports_gallery_grid(page_size: int = PAGE_SIZE_DEFAULT, key_prefix: str = "") -> None:
92
+ """Grade com miniaturas + download; exclusão apenas para Admin (server-side check)."""
93
+ st.subheader("🖼️ Galeria de Relatórios")
94
+ imgs = gallery_list_images_sorted()
95
+ if not imgs:
96
+ st.info("Ainda não há imagens publicadas.")
97
+ return
98
+
99
+ import math
100
+
101
+ total = len(imgs)
102
+ pages = max(1, math.ceil(total / page_size))
103
+
104
+ key_page = f"{key_prefix}gallery_page"
105
+ st.session_state.setdefault(key_page, 1)
106
+
107
+ cur_page = st.session_state[key_page]
108
+ if cur_page > pages:
109
+ cur_page = pages
110
+ st.session_state[key_page] = cur_page
111
+ if cur_page < 1:
112
+ cur_page = 1
113
+ st.session_state[key_page] = cur_page
114
+
115
+ col_left, col_center, col_right = st.columns([1, 3, 1])
116
+ with col_left:
117
+ if st.button("⬅️", disabled=(cur_page <= 1), key=f"{key_prefix}gallery_nav_prev"):
118
+ st.session_state[key_page] = max(1, cur_page - 1)
119
+ st.rerun()
120
+ with col_center:
121
+ sel = st.selectbox(
122
+ "Página",
123
+ options=list(range(1, pages + 1)),
124
+ index=cur_page - 1,
125
+ key=f"{key_prefix}gallery_page_select",
126
+ label_visibility="collapsed",
127
+ )
128
+ if sel != cur_page:
129
+ st.session_state[key_page] = sel
130
+ st.rerun()
131
+ with col_right:
132
+ if st.button("➡️", disabled=(cur_page >= pages), key=f"{key_prefix}gallery_nav_next"):
133
+ st.session_state[key_page] = min(pages, cur_page + 1)
134
+ st.rerun()
135
+
136
+ st.caption(
137
+ f"Mostrando {page_size} por página — {total} imagens no total · "
138
+ f"Página {st.session_state.get(key_page, 1)} de {pages}"
139
+ )
140
+
141
+ start = (st.session_state[key_page] - 1) * page_size
142
+ end = min(start + page_size, total)
143
+ page_items = imgs[start:end]
144
+
145
+ cols = st.columns(3)
146
+ is_admin = bool(st.session_state.get("is_admin"))
147
+
148
+ for i, (name, mtime, orig_path, thumb_path) in enumerate(page_items):
149
+ col = cols[i % 3]
150
+ with col:
151
+ try:
152
+ if Path(thumb_path).exists():
153
+ col.image(str(thumb_path), use_container_width=True, caption=name)
154
+ else:
155
+ col.image(str(orig_path), use_container_width=True, caption=name)
156
+ except Exception:
157
+ col.warning(f"Não foi possível carregar {name}.")
158
+ continue
159
+
160
+ # Download do original
161
+ try:
162
+ with open(orig_path, "rb") as f:
163
+ mime = "image/jpeg" if name.lower().endswith((".jpg", ".jpeg")) else "image/png"
164
+ st.download_button(
165
+ label="⬇️ Baixar original",
166
+ data=f,
167
+ file_name=name,
168
+ mime=mime,
169
+ use_container_width=True,
170
+ key=f"{key_prefix}dl_{name}",
171
+ )
172
+ except Exception as e:
173
+ col.warning(f"Download indisponível: {e}")
174
+
175
+ # Exclusão — somente Admin (verificação também no servidor)
176
+ if is_admin:
177
+ if st.button("🗑️ Remover", key=f"{key_prefix}rm_{name}", type="secondary", use_container_width=True):
178
+ try:
179
+ delete_report_image(filename=name, is_admin=True)
180
+ st.success("Imagem removida.")
181
+ st.rerun()
182
+ except PermissionError as e:
183
+ st.error(str(e))
184
+ except Exception as e:
185
+ st.error(f"Erro ao remover: {e}")
186
+ else:
187
+ st.caption("Somente Admin pode excluir.")
188
+
189
+
190
+ def aba_galeria_relatorios(context_key: str) -> None:
191
+ """Aba completa: upload + grid (keys isoladas por contexto)."""
192
+ with st.container(border=True):
193
+ render_reports_gallery_uploader(key_prefix=context_key)
194
+ st.divider()
195
+ render_reports_gallery_grid(page_size=PAGE_SIZE_DEFAULT, key_prefix=context_key)
gallery_storage.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gallery_storage.py
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ from pathlib import Path
5
+ from typing import List, Tuple, Optional
6
+ from PIL import Image, ImageOps
7
+
8
+ # Settings: aceita Config/ e config/; se não achar, usa defaults
9
+ try:
10
+ from Config.settings import GALLERY_DIR, THUMB_DIR, GALLERY_ALLOWED_EXT, THUMB_MAX
11
+ except Exception:
12
+ try:
13
+ from config.settings import GALLERY_DIR, THUMB_DIR, GALLERY_ALLOWED_EXT, THUMB_MAX
14
+ except Exception:
15
+ # Fallbacks seguros
16
+ BASE_DIR = Path(__file__).resolve().parent
17
+ DATA_DIR = BASE_DIR / "data"
18
+ GALLERY_DIR = DATA_DIR / "reports_photos"
19
+ THUMB_DIR = GALLERY_DIR / "_thumbs"
20
+ GALLERY_ALLOWED_EXT = {".png", ".jpg", ".jpeg", ".webp"}
21
+ THUMB_MAX = (512, 512)
22
+
23
+ GALLERY_DIR.mkdir(parents=True, exist_ok=True)
24
+ THUMB_DIR.mkdir(parents=True, exist_ok=True)
25
+
26
+ def _gallery_is_image(filename: str) -> bool:
27
+ ext = os.path.splitext(filename)[1].lower()
28
+ return ext in GALLERY_ALLOWED_EXT
29
+
30
+ def _gallery_safe_name(base: str) -> str:
31
+ return "".join(c for c in base if c.isalnum() or c in ("-", "_")).strip("_")
32
+
33
+ def _thumb_path_for(orig_path: Path) -> Path:
34
+ base = orig_path.stem
35
+ return THUMB_DIR / f"{base}-thumb-{THUMB_MAX[0]}x{THUMB_MAX[1]}.jpg"
36
+
37
+ def _generate_thumbnail(orig_path: Path, thumb_path: Path) -> None:
38
+ try:
39
+ with Image.open(orig_path) as im:
40
+ im = ImageOps.exif_transpose(im)
41
+ if im.mode in ("RGBA", "LA"):
42
+ bg = Image.new("RGB", im.size, (255, 255, 255))
43
+ bg.paste(im, mask=im.split()[-1])
44
+ im = bg
45
+ elif im.mode != "RGB":
46
+ im = im.convert("RGB")
47
+ im.thumbnail(THUMB_MAX)
48
+ thumb_path.parent.mkdir(parents=True, exist_ok=True)
49
+ im.save(str(thumb_path), "JPEG", quality=85, optimize=True, progressive=True)
50
+ except Exception as e:
51
+ print(f"[thumb] Falha ao gerar miniatura para {orig_path}: {e}")
52
+
53
+ def _ensure_thumbnail(orig_path: Path) -> Path:
54
+ tpath = _thumb_path_for(orig_path)
55
+ try:
56
+ orig_mtime = orig_path.stat().st_mtime
57
+ thumb_mtime = tpath.stat().st_mtime if tpath.exists() else -1
58
+ if thumb_mtime < orig_mtime:
59
+ _generate_thumbnail(orig_path, tpath)
60
+ except Exception as e:
61
+ print(f"[thumb] Erro: {e}")
62
+ return tpath
63
+
64
+ def gallery_list_images_sorted() -> List[Tuple[str, float, Path, Path]]:
65
+ """
66
+ [(nome, mtime, caminho_original, caminho_thumb)] do mais novo ao mais antigo.
67
+ """
68
+ if not GALLERY_DIR.is_dir():
69
+ return []
70
+ items = []
71
+ for name in os.listdir(GALLERY_DIR):
72
+ full = GALLERY_DIR / name
73
+ if full.is_file() and _gallery_is_image(name):
74
+ try:
75
+ mtime = full.stat().st_mtime
76
+ tpath = _ensure_thumbnail(full)
77
+ items.append((name, mtime, full, tpath))
78
+ except Exception:
79
+ continue
80
+ items.sort(key=lambda t: t[1], reverse=True)
81
+ return items
82
+
83
+ def save_report_image(uploaded_file, uploader_name: Optional[str] = None, uploader_email: Optional[str] = None) -> Optional[Path]:
84
+ if uploaded_file is None:
85
+ return None
86
+
87
+ base, ext = os.path.splitext(uploaded_file.name or "")
88
+ ext = ext.lower()
89
+ if ext not in GALLERY_ALLOWED_EXT:
90
+ raise ValueError("Formato não suportado. Use PNG/JPG/JPEG/WEBP.")
91
+
92
+ who_bits = []
93
+ if uploader_name: who_bits.append(_gallery_safe_name(uploader_name))
94
+ if uploader_email: who_bits.append(_gallery_safe_name((uploader_email or "").split("@")[0]))
95
+ who_str = ("-" + "-".join(filter(None, who_bits))) if who_bits else ""
96
+
97
+ from datetime import datetime
98
+ ts = datetime.now().strftime("%Y%m%d-%H%M%S")
99
+ safe_base = _gallery_safe_name(base) or "relatorio"
100
+ fname = f"{ts}-{safe_base}{who_str}{ext}"
101
+ dest = GALLERY_DIR / fname
102
+
103
+ img = Image.open(uploaded_file)
104
+ img = ImageOps.exif_transpose(img)
105
+ if ext in (".jpg", ".jpeg") and img.mode not in ("RGB",):
106
+ img = img.convert("RGB")
107
+ img.save(dest)
108
+ _ensure_thumbnail(dest)
109
+ return dest
110
+
111
+ def delete_report_image(filename: str, is_admin: bool) -> None:
112
+ """
113
+ Exclui (original + thumb) de forma segura e restrita a Admin.
114
+ - Protege contra path traversal (só apaga dentro de GALLERY_DIR)
115
+ """
116
+ if not is_admin:
117
+ raise PermissionError("Somente Admin pode excluir imagens.")
118
+ if "/" in filename or "\\" in filename:
119
+ raise ValueError("Nome de arquivo inválido.")
120
+ target = (GALLERY_DIR / filename).resolve()
121
+ if GALLERY_DIR.resolve() not in target.parents and target != GALLERY_DIR.resolve():
122
+ raise ValueError("Caminho inválido.")
123
+ if target.exists():
124
+ target.unlink()
125
+ tpath = _thumb_path_for(target)
126
+ if tpath.exists():
127
+ tpath.unlink()
models.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # models.py
2
+ # -*- coding: utf-8 -*-
3
+ from datetime import datetime, date, time
4
+ from sqlalchemy import (
5
+ Column, Integer, String, Text, Date, Time, DateTime, Float, ForeignKey, Index
6
+ )
7
+ from sqlalchemy.orm import declarative_base, relationship
8
+
9
+ Base = declarative_base()
10
+
11
+
12
+ class Course(Base):
13
+ __tablename__ = "courses"
14
+
15
+ id = Column(Integer, primary_key=True, autoincrement=True)
16
+ title = Column(String(255), nullable=False, index=True)
17
+ description = Column(Text, nullable=True)
18
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
19
+
20
+ lessons = relationship("Lesson", back_populates="course", cascade="all, delete-orphan")
21
+ materials = relationship("Material", back_populates="course", cascade="all, delete-orphan")
22
+ schedule_items = relationship("Schedule", back_populates="course", cascade="all, delete-orphan")
23
+ enrollments = relationship("Enrollment", back_populates="course", cascade="all, delete-orphan")
24
+ grades = relationship("Grade", back_populates="course", cascade="all, delete-orphan")
25
+ certificates = relationship("Certificate", back_populates="course", cascade="all, delete-orphan")
26
+ makeups = relationship("MakeupRequest", back_populates="course", cascade="all, delete-orphan")
27
+
28
+
29
+ class Lesson(Base):
30
+ __tablename__ = "lessons"
31
+
32
+ id = Column(Integer, primary_key=True, autoincrement=True)
33
+ course_id = Column(Integer, ForeignKey("courses.id", ondelete="CASCADE"), nullable=False, index=True)
34
+ title = Column(String(255), nullable=False)
35
+ description = Column(Text, nullable=True)
36
+ video_path = Column(Text, nullable=True) # pode ser URL (YouTube) ou caminho local
37
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
38
+
39
+ course = relationship("Course", back_populates="lessons")
40
+
41
+
42
+ class Material(Base):
43
+ __tablename__ = "materials"
44
+
45
+ id = Column(Integer, primary_key=True, autoincrement=True)
46
+ course_id = Column(Integer, ForeignKey("courses.id", ondelete="CASCADE"), nullable=False, index=True)
47
+ title = Column(String(255), nullable=False)
48
+ description = Column(Text, nullable=True)
49
+ pdf_path = Column(Text, nullable=True)
50
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
51
+
52
+ course = relationship("Course", back_populates="materials")
53
+
54
+
55
+ class Schedule(Base):
56
+ __tablename__ = "schedule"
57
+
58
+ id = Column(Integer, primary_key=True, autoincrement=True)
59
+ course_id = Column(Integer, ForeignKey("courses.id", ondelete="CASCADE"), nullable=False, index=True)
60
+
61
+ class_date = Column(Date, nullable=True)
62
+ start_time = Column(Time, nullable=True)
63
+ end_time = Column(Time, nullable=True)
64
+
65
+ # Campo 'topic' guarda JSON/texto com metadados (topic/module_id/assigned_emails/…)
66
+ topic = Column(Text, nullable=True)
67
+
68
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
69
+
70
+ course = relationship("Course", back_populates="schedule_items")
71
+
72
+ # Acelera buscas por data/hora por curso
73
+ Index("ix_schedule_course_date", Schedule.course_id, Schedule.class_date, Schedule.start_time)
74
+
75
+
76
+ class Enrollment(Base):
77
+ __tablename__ = "enrollments"
78
+
79
+ id = Column(Integer, primary_key=True, autoincrement=True)
80
+ course_id = Column(Integer, ForeignKey("courses.id", ondelete="CASCADE"), nullable=False, index=True)
81
+ student_name = Column(String(255), nullable=True)
82
+ student_email = Column(String(255), nullable=False, index=True) # armazenar em minúsculas
83
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
84
+
85
+ course = relationship("Course", back_populates="enrollments")
86
+
87
+ # Evita duplicidade de matrícula do mesmo email no mesmo curso (lógica no app faz dedupe também)
88
+ Index("ix_enrollment_course_email", Enrollment.course_id, Enrollment.student_email)
89
+
90
+
91
+ class Grade(Base):
92
+ __tablename__ = "grades"
93
+
94
+ id = Column(Integer, primary_key=True, autoincrement=True)
95
+ course_id = Column(Integer, ForeignKey("courses.id", ondelete="CASCADE"), nullable=False, index=True)
96
+ student_name = Column(String(255), nullable=True)
97
+ student_email = Column(String(255), nullable=False, index=True)
98
+ grade = Column(Float, nullable=True)
99
+ note = Column(Text, nullable=True)
100
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
101
+
102
+ course = relationship("Course", back_populates="grades")
103
+
104
+
105
+ class MakeupRequest(Base):
106
+ __tablename__ = "makeup_requests"
107
+
108
+ id = Column(Integer, primary_key=True, autoincrement=True)
109
+ course_id = Column(Integer, ForeignKey("courses.id", ondelete="CASCADE"), nullable=False, index=True)
110
+ student_name = Column(String(255), nullable=False)
111
+ student_email = Column(String(255), nullable=False, index=True)
112
+ requested_date = Column(Date, nullable=True)
113
+ note = Column(Text, nullable=True)
114
+ status = Column(String(32), default="pending", nullable=False) # pending/approved/denied
115
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
116
+
117
+ course = relationship("Course", back_populates="makeups")
118
+
119
+
120
+ class Certificate(Base):
121
+ __tablename__ = "certificates"
122
+
123
+ id = Column(Integer, primary_key=True, autoincrement=True)
124
+ course_id = Column(Integer, ForeignKey("courses.id", ondelete="CASCADE"), nullable=False, index=True)
125
+ student_name = Column(String(255), nullable=False)
126
+ student_email = Column(String(255), nullable=False, index=True)
127
+ pdf_path = Column(Text, nullable=True)
128
+ issued_at = Column(DateTime, nullable=True, index=True)
129
+
130
+ course = relationship("Course", back_populates="certificates")
presence.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/presence.py
2
+ import os
3
+ import sqlite3
4
+ import pandas as pd
5
+ from db import DB_PATH
6
+
7
+ PRESENCE_ONLINE_THRESHOLD_SEC = 180
8
+
9
+ def _ensure_presence_table() -> None:
10
+ os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
11
+ with sqlite3.connect(DB_PATH) as conn:
12
+ c = conn.cursor()
13
+ c.execute(
14
+ """
15
+ CREATE TABLE IF NOT EXISTS presence (
16
+ session_id TEXT PRIMARY KEY,
17
+ user_email TEXT,
18
+ user_name TEXT,
19
+ role TEXT,
20
+ page TEXT,
21
+ first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
22
+ last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP
23
+ )
24
+ """
25
+ )
26
+ conn.commit()
27
+
28
+ def update_presence(role: str, page: str, user_email: str | None, user_name: str | None) -> None:
29
+ _ensure_presence_table()
30
+ import streamlit as st
31
+ from uuid import uuid4
32
+ sid = st.session_state.get("session_id") or str(uuid4())
33
+ st.session_state["session_id"] = sid
34
+ with sqlite3.connect(DB_PATH) as conn:
35
+ c = conn.cursor()
36
+ c.execute(
37
+ """
38
+ INSERT INTO presence (session_id, user_email, user_name, role, page, first_seen, last_seen)
39
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
40
+ ON CONFLICT(session_id)
41
+ DO UPDATE SET user_email=excluded.user_email, user_name=excluded.user_name,
42
+ role=excluded.role, page=excluded.page, last_seen=CURRENT_TIMESTAMP
43
+ """,
44
+ (sid, (user_email or None), (user_name or None), role, page)
45
+ )
46
+ conn.commit()
47
+
48
+ def get_online_users(threshold_sec: int = PRESENCE_ONLINE_THRESHOLD_SEC) -> pd.DataFrame:
49
+ _ensure_presence_table()
50
+ with sqlite3.connect(DB_PATH) as conn:
51
+ q = f"""
52
+ SELECT session_id, user_email, user_name, role, page, first_seen, last_seen,
53
+ CAST(strftime('%s', 'now') - strftime('%s', last_seen) AS INTEGER) AS idle_sec,
54
+ CAST(strftime('%s', 'now') - strftime('%s', first_seen) AS INTEGER) AS session_sec
55
+ FROM presence
56
+ WHERE (strftime('%s', 'now') - strftime('%s', last_seen)) <= ?
57
+ ORDER BY last_seen DESC
58
+ """
59
+ df = pd.read_sql_query(q, conn, params=(threshold_sec,))
60
+ return df
requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.40.1
2
+ sqlalchemy==2.0.29
3
+ pandas==2.2.2
4
+ reportlab==4.1.0
5
+ openpyxl==3.1.2
6
+ plotly>=5.18.0
7
+ streamlit-calendar==0.5.0
8
+ psycopg2-binary==2.9.9
9
+
10
+ streamlit>=1.30
11
+ streamlit-calendar>=0.4.0
12
+ SQLAlchemy>=2.0
13
+ pandas>=2.0
14
+ plotly>=5.17
15
+ openpyxl>=3.1
16
+ reportlab>=4.0
17
+ PyPDF2>=3.0
18
+ streamlit>=1.33
19
+ streamlit-calendar>=0.5.0
20
+ huggingface_hub>=0.21.4
student_auth.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/student_auth.py
2
+ import os
3
+ import sqlite3
4
+ import hashlib
5
+ from typing import Optional
6
+ from db import DB_PATH
7
+
8
+ def _ensure_auth_table() -> None:
9
+ os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
10
+ with sqlite3.connect(DB_PATH) as conn:
11
+ c = conn.cursor()
12
+ c.execute(
13
+ """
14
+ CREATE TABLE IF NOT EXISTS student_auth (
15
+ student_email TEXT PRIMARY KEY,
16
+ password_hash TEXT NOT NULL,
17
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
18
+ )
19
+ """
20
+ )
21
+ conn.commit()
22
+
23
+ def _hash_password(plain: str) -> str:
24
+ salt = os.urandom(16).hex()
25
+ h = hashlib.sha256((salt + plain).encode("utf-8")).hexdigest()
26
+ return f"{salt}${h}"
27
+
28
+ def _verify_password(stored: str, plain: str) -> bool:
29
+ try:
30
+ salt, h = stored.split("$", 1)
31
+ calc = hashlib.sha256((salt + plain).encode("utf-8")).hexdigest()
32
+ return h == calc
33
+ except Exception:
34
+ return False
35
+
36
+ def set_student_password(email: str, plain: str) -> None:
37
+ if not email or not plain:
38
+ raise ValueError("E-mail e senha são obrigatórios.")
39
+ _ensure_auth_table()
40
+ hp = _hash_password(plain)
41
+ with sqlite3.connect(DB_PATH) as conn:
42
+ c = conn.cursor()
43
+ c.execute(
44
+ """
45
+ INSERT INTO student_auth (student_email, password_hash) VALUES (?, ?)
46
+ ON CONFLICT(student_email) DO UPDATE SET password_hash=excluded.password_hash, created_at=CURRENT_TIMESTAMP
47
+ """,
48
+ (email.strip().lower(), hp),
49
+ )
50
+ conn.commit()
51
+
52
+ def has_student_password(email: str) -> bool:
53
+ if not email:
54
+ return False
55
+ _ensure_auth_table()
56
+ with sqlite3.connect(DB_PATH) as conn:
57
+ c = conn.cursor()
58
+ c.execute("SELECT 1 FROM student_auth WHERE student_email=?", (email.strip().lower(),))
59
+ return c.fetchone() is not None
60
+
61
+ def check_student_password(email: str, plain: str) -> bool:
62
+ if not email or not plain:
63
+ return False
64
+ _ensure_auth_table()
65
+ with sqlite3.connect(DB_PATH) as conn:
66
+ c = conn.cursor()
67
+ c.execute("SELECT password_hash FROM student_auth WHERE student_email=?", (email.strip().lower(),))
68
+ row = c.fetchone()
69
+ if not row:
70
+ return False
71
+ return _verify_password(row[0], plain)
utils.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import io
4
+ import hashlib
5
+ from datetime import datetime
6
+ from typing import Optional
7
+ from reportlab.pdfgen import canvas
8
+ from reportlab.lib.pagesizes import A4
9
+ from reportlab.lib.units import cm
10
+ from reportlab.lib import colors
11
+ import streamlit as st
12
+
13
+ # Credenciais de admin via env (defina no Hugging Face Space Settings)
14
+ ADMIN_USER = os.environ.get("ADMIN_USER", "admin")
15
+ # Armazena hash sha256 da senha; por padrão 'admin'
16
+ _admin_pass_default = os.environ.get("ADMIN_PASS", "admin")
17
+ ADMIN_PASS_HASH = hashlib.sha256(_admin_pass_default.encode()).hexdigest()
18
+
19
+ def ensure_dirs():
20
+ os.makedirs("data", exist_ok=True)
21
+ os.makedirs("data/videos", exist_ok=True)
22
+ os.makedirs("data/pdfs", exist_ok=True)
23
+ os.makedirs("data/certificates", exist_ok=True)
24
+
25
+ def save_uploaded_file(file, base_dir="data") -> str:
26
+ ensure_dirs()
27
+ filename = file.name
28
+ safe_name = f"{int(datetime.utcnow().timestamp())}_{filename}"
29
+ out_path = os.path.join(base_dir, safe_name)
30
+ with open(out_path, "wb") as f:
31
+ f.write(file.getbuffer())
32
+ return out_path
33
+
34
+ def human_dt(dt: Optional[datetime]) -> str:
35
+ if not dt:
36
+ return "—"
37
+ return dt.strftime("%d/%m/%Y %H:%M")
38
+
39
+ def generate_certificate_pdf(student_name: str, course_title: str) -> str:
40
+ ensure_dirs()
41
+ fname = f"cert_{int(datetime.utcnow().timestamp())}.pdf"
42
+ out_path = os.path.join("data/certificates", fname)
43
+
44
+ c = canvas.Canvas(out_path, pagesize=A4)
45
+ w, h = A4
46
+
47
+ # Moldura simples
48
+ c.setStrokeColor(colors.HexColor("#2c3e50"))
49
+ c.setLineWidth(6)
50
+ c.rect(1*cm, 1*cm, w-2*cm, h-2*cm)
51
+
52
+ # Título
53
+ c.setFillColor(colors.HexColor("#2c3e50"))
54
+ c.setFont("Helvetica-Bold", 28)
55
+ c.drawCentredString(w/2, h-5*cm, "CERTIFICADO DE CONCLUSÃO")
56
+
57
+ # Texto principal
58
+ c.setFillColor(colors.black)
59
+ c.setFont("Helvetica", 14)
60
+ text = (
61
+ f"Certificamos que {student_name} concluiu com êxito o curso '{course_title}'."
62
+ )
63
+ c.drawCentredString(w/2, h-8*cm, text)
64
+
65
+ # Data
66
+ c.setFont("Helvetica-Oblique", 12)
67
+ c.drawCentredString(w/2, h-10*cm, datetime.now().strftime("Emitido em %d/%m/%Y"))
68
+
69
+ # Assinatura (placeholder)
70
+ c.line(w/2-5*cm, 4*cm, w/2+5*cm, 4*cm)
71
+ c.setFont("Helvetica", 10)
72
+ c.drawCentredString(w/2, 3.5*cm, "Coordenação — ARM Logística")
73
+
74
+ c.showPage()
75
+ c.save()
76
+ return out_path
video_access.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/video_access.py
2
+ import os
3
+ import sqlite3
4
+ from typing import List, Optional
5
+ from db import DB_PATH
6
+
7
+ def _ensure_video_access_tables() -> None:
8
+ os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
9
+ with sqlite3.connect(DB_PATH) as conn:
10
+ c = conn.cursor()
11
+ c.execute(
12
+ """
13
+ CREATE TABLE IF NOT EXISTS video_access (
14
+ lesson_id INTEGER PRIMARY KEY,
15
+ visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public','restricted','private')),
16
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
17
+ )
18
+ """
19
+ )
20
+ c.execute(
21
+ """
22
+ CREATE TABLE IF NOT EXISTS video_access_list (
23
+ lesson_id INTEGER NOT NULL,
24
+ student_email TEXT NOT NULL,
25
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
26
+ UNIQUE(lesson_id, student_email)
27
+ )
28
+ """
29
+ )
30
+ conn.commit()
31
+
32
+ _ensure_video_access_tables()
33
+
34
+ def get_video_visibility(lesson_id: int) -> str:
35
+ with sqlite3.connect(DB_PATH) as conn:
36
+ c = conn.cursor()
37
+ c.execute("SELECT visibility FROM video_access WHERE lesson_id=?", (lesson_id,))
38
+ row = c.fetchone()
39
+ return row[0] if row and row[0] else "public"
40
+
41
+ def set_video_visibility(lesson_id: int, visibility: str) -> None:
42
+ if visibility not in ("public", "restricted", "private"):
43
+ raise ValueError("visibility deve ser 'public', 'restricted' ou 'private'")
44
+ with sqlite3.connect(DB_PATH) as conn:
45
+ c = conn.cursor()
46
+ c.execute(
47
+ """
48
+ INSERT INTO video_access (lesson_id, visibility, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
49
+ ON CONFLICT(lesson_id) DO UPDATE SET visibility=excluded.visibility, updated_at=CURRENT_TIMESTAMP
50
+ """,
51
+ (lesson_id, visibility),
52
+ )
53
+ conn.commit()
54
+
55
+ def get_video_acl_emails(lesson_id: int) -> List[str]:
56
+ with sqlite3.connect(DB_PATH) as conn:
57
+ c = conn.cursor()
58
+ c.execute("SELECT student_email FROM video_access_list WHERE lesson_id=?", (lesson_id,))
59
+ rows = c.fetchall()
60
+ return [r[0] for r in rows] if rows else []
61
+
62
+ def set_video_acl_emails(lesson_id: int, emails: List[str]) -> None:
63
+ emails_clean = sorted({(e or "").strip().lower() for e in emails if (e or "").strip()})
64
+ with sqlite3.connect(DB_PATH) as conn:
65
+ c = conn.cursor()
66
+ c.execute("DELETE FROM video_access_list WHERE lesson_id=?", (lesson_id,))
67
+ if emails_clean:
68
+ c.executemany(
69
+ "INSERT INTO video_access_list (lesson_id, student_email) VALUES (?, ?)",
70
+ [(lesson_id, e) for e in emails_clean]
71
+ )
72
+ conn.commit()
73
+
74
+ def is_video_allowed_for_student(lesson_id: int, student_email: Optional[str], is_admin: bool) -> bool:
75
+ if is_admin:
76
+ return True
77
+ vis = get_video_visibility(lesson_id)
78
+ if vis == "public":
79
+ return bool(student_email)
80
+ if vis == "private":
81
+ return False
82
+ if vis == "restricted":
83
+ if not student_email:
84
+ return False
85
+ allow = get_video_acl_emails(lesson_id)
86
+ return student_email.strip().lower() in {e.strip().lower() for e in allow}
87
+ return False