VeuReu commited on
Commit
e5fd4ee
1 Parent(s): 758eede

Upload 3 files

Browse files
Files changed (3) hide show
  1. auth.py +1 -1
  2. config.yaml +1 -1
  3. databases.py +191 -0
auth.py CHANGED
@@ -5,7 +5,7 @@ Gestiona usuarios, verificaci贸n de contrase帽as y sincronizaci贸n de usuarios p
5
  import sys
6
  import streamlit as st
7
  from datetime import datetime
8
- from database import get_user, create_user, update_user_password, get_all_users
9
  from mobile_verification import (
10
  initialize_sms_state,
11
  render_mobile_verification_screen,
 
5
  import sys
6
  import streamlit as st
7
  from datetime import datetime
8
+ from databases import get_user, create_user, update_user_password, get_all_users
9
  from mobile_verification import (
10
  initialize_sms_state,
11
  render_mobile_verification_screen,
config.yaml CHANGED
@@ -21,7 +21,7 @@ storage:
21
 
22
  sqlite:
23
  # base de datos SQLite local del space
24
- path: "data/app.db"
25
 
26
  security:
27
  # coste de bcrypt (m谩s alto = m谩s seguro pero m谩s lento)
 
21
 
22
  sqlite:
23
  # base de datos SQLite local del space
24
+ path: "data/login.db"
25
 
26
  security:
27
  # coste de bcrypt (m谩s alto = m谩s seguro pero m谩s lento)
databases.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sqlite3
3
+ from contextlib import contextmanager
4
+ from typing import Optional, Dict, Any, List, Tuple
5
+ from datetime import datetime
6
+
7
+ # Reutilizamos la misma l贸gica que antes, pero centralizada en este m贸dulo
8
+
9
+ DEFAULT_DB_PATH = None # set by set_db_path at runtime
10
+
11
+
12
+ def set_db_path(db_path: str):
13
+ global DEFAULT_DB_PATH
14
+ DEFAULT_DB_PATH = db_path
15
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
16
+
17
+
18
+ def get_connection():
19
+ if not DEFAULT_DB_PATH:
20
+ raise ValueError("Database path not set. Call set_db_path(path) first.")
21
+ return sqlite3.connect(DEFAULT_DB_PATH)
22
+
23
+
24
+ @contextmanager
25
+ def get_conn(db_path: Optional[str] = None):
26
+ path = db_path or DEFAULT_DB_PATH
27
+ conn = sqlite3.connect(path, check_same_thread=False)
28
+ conn.row_factory = sqlite3.Row
29
+ try:
30
+ yield conn
31
+ conn.commit()
32
+ finally:
33
+ conn.close()
34
+
35
+
36
+ def init_schema():
37
+ with get_conn() as conn:
38
+ c = conn.cursor()
39
+ # (tus tablas existentes)
40
+ c.execute(
41
+ """
42
+ CREATE TABLE IF NOT EXISTS users (
43
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
44
+ username TEXT UNIQUE NOT NULL,
45
+ password_hash TEXT,
46
+ role TEXT NOT NULL,
47
+ created_at TEXT NOT NULL
48
+ );
49
+ """
50
+ )
51
+ # Migraciones: asegurar columnas esperadas
52
+ try:
53
+ c.execute("PRAGMA table_info(users)")
54
+ cols = {row[1] for row in c.fetchall()} # set de nombres de columnas
55
+ if "password_hash" not in cols:
56
+ c.execute("ALTER TABLE users ADD COLUMN password_hash TEXT")
57
+ if "role" not in cols:
58
+ c.execute("ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'verd'")
59
+ if "created_at" not in cols:
60
+ c.execute("ALTER TABLE users ADD COLUMN created_at TEXT NOT NULL DEFAULT ''")
61
+ except sqlite3.OperationalError:
62
+ pass
63
+ # Intento de limpieza de columna antigua si existiera (SQLite no permite DROP COLUMN en versiones antiguas)
64
+ try:
65
+ c.execute("ALTER TABLE users DROP COLUMN pw_hash;")
66
+ except sqlite3.OperationalError:
67
+ pass
68
+ # (opcional: tus otras tablas)
69
+
70
+ # >>> TABLA PARA FEEDBACK DE AD (no depende de videos)
71
+ c.execute(
72
+ """
73
+ CREATE TABLE IF NOT EXISTS feedback_ad (
74
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
75
+ video_name TEXT NOT NULL, -- nombre de carpeta dentro de videos/completed
76
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
77
+ transcripcio INTEGER NOT NULL, -- 1..10
78
+ identificacio INTEGER NOT NULL, -- 1..10
79
+ localitzacions INTEGER NOT NULL, -- 1..10
80
+ activitats INTEGER NOT NULL, -- 1..10
81
+ narracions INTEGER NOT NULL, -- 1..10
82
+ expressivitat INTEGER NOT NULL, -- 1..10
83
+ comments TEXT,
84
+ created_at TEXT NOT NULL
85
+ );
86
+ """
87
+ )
88
+ # Add column if it doesn't exist, for backwards compatibility
89
+ try:
90
+ c.execute(
91
+ "ALTER TABLE feedback_ad ADD COLUMN expressivitat INTEGER NOT NULL DEFAULT 7;"
92
+ )
93
+ except sqlite3.OperationalError:
94
+ pass # column already exists
95
+
96
+
97
+ def add_feedback_ad(
98
+ video_name: str,
99
+ user_id: int,
100
+ transcripcio: int,
101
+ identificacio: int,
102
+ localitzacions: int,
103
+ activitats: int,
104
+ narracions: int,
105
+ expressivitat: int,
106
+ comments: str | None,
107
+ ):
108
+ with get_conn() as conn:
109
+ conn.execute(
110
+ """INSERT INTO feedback_ad
111
+ (video_name, user_id, transcripcio, identificacio, localitzacions, activitats, narracions, expressivitat, comments, created_at)
112
+ VALUES (?,?,?,?,?,?,?,?,?,?)""",
113
+ (
114
+ video_name,
115
+ user_id,
116
+ transcripcio,
117
+ identificacio,
118
+ localitzacions,
119
+ activitats,
120
+ narracions,
121
+ expressivitat,
122
+ comments,
123
+ now_str(),
124
+ ),
125
+ )
126
+
127
+
128
+ def get_feedback_ad_for_video(video_name: str):
129
+ with get_conn() as conn:
130
+ cur = conn.execute(
131
+ """SELECT * FROM feedback_ad WHERE video_name=? ORDER BY created_at DESC""",
132
+ (video_name,),
133
+ )
134
+ return cur.fetchall()
135
+
136
+
137
+ def get_feedback_ad_stats():
138
+ # medias por v铆deo y ranking
139
+ with get_conn() as conn:
140
+ cur = conn.execute(
141
+ """
142
+ SELECT
143
+ video_name,
144
+ COUNT(*) AS n,
145
+ AVG(transcripcio) AS avg_transcripcio,
146
+ AVG(identificacio) AS avg_identificacio,
147
+ AVG(localitzacions) AS avg_localitzacions,
148
+ AVG(activitats) AS avg_activitats,
149
+ AVG(narracions) AS avg_narracions,
150
+ AVG(expressivitat) AS avg_expressivitat,
151
+ (AVG(transcripcio)+AVG(identificacio)+AVG(localitzacions)+AVG(activitats)+AVG(narracions)+AVG(expressivitat))/6.0 AS avg_global
152
+ FROM feedback_ad
153
+ GROUP BY video_name
154
+ ORDER BY avg_global DESC, n DESC;
155
+ """
156
+ )
157
+ return cur.fetchall()
158
+
159
+
160
+ def now_str():
161
+ return datetime.utcnow().isoformat(timespec="seconds") + "Z"
162
+
163
+
164
+ # Users
165
+
166
+ def create_user(username: str, password_hash: str, role: str):
167
+ with get_conn() as conn:
168
+ conn.execute(
169
+ "INSERT INTO users(username, password_hash, role, created_at) VALUES (?,?,?,?)",
170
+ (username, password_hash, role, now_str()),
171
+ )
172
+
173
+
174
+ def get_user(username: str):
175
+ with get_conn() as conn:
176
+ cur = conn.execute("SELECT * FROM users WHERE username=?", (username,))
177
+ return cur.fetchone()
178
+
179
+
180
+ def get_all_users() -> List[Dict[str, Any]]:
181
+ with get_conn() as conn:
182
+ cur = conn.execute("SELECT id, username, role FROM users ORDER BY username")
183
+ return cur.fetchall()
184
+
185
+
186
+ def update_user_password(username: str, password_hash: str):
187
+ with get_conn() as conn:
188
+ conn.execute(
189
+ "UPDATE users SET password_hash = ? WHERE username = ?",
190
+ (password_hash, username),
191
+ )