mstts / utils.py
tayyardurden's picture
Update utils.py
37faa13 verified
Raw History Blame Contribute Delete
3.66 kB
import psycopg2
import streamlit as st
import os
import datetime
from dotenv import load_dotenv
load_dotenv()
@st.cache_resource
def get_db_connection():
db_name = os.getenv('DB_NAME')
db_user = os.getenv('DB_USER')
db_password = os.getenv('DB_PASSWORD')
db_host = os.getenv('DB_HOST')
db_port = os.getenv('DB_PORT')
if not all([db_name, db_user, db_password, db_host, db_port]):
raise ValueError("Database configuration is incomplete. Please check your environment variables.")
try:
conn = psycopg2.connect(
dbname=db_name,
user=db_user,
password=db_password,
host=db_host,
port=db_port
)
conn.autocommit = True
return conn
except psycopg2.OperationalError as e:
st.error(f"Error connecting to the database: {e}")
return None
def check_and_insert_user(conn, username):
cursor = conn.cursor()
cursor.execute("SELECT user_id FROM users WHERE username = %s", (str(username),))
user = cursor.fetchone()
if user is None:
raise ValueError("User not found")
user_id = user[0]
# Ensure login_time is initialized
if 'login_time' not in st.session_state:
st.session_state.login_time = datetime.datetime.now()
# Use the login time and user_id to generate a consistent and unique survey_id
login_time = st.session_state.login_time
survey_id = int(f"{user_id}{login_time.strftime('%H%M%S')}")
st.session_state.survey_id = survey_id
# Check if the survey_id already exists in the survey_status table
cursor.execute("SELECT survey_id FROM survey_status WHERE survey_id = %s", (survey_id,))
existing_survey = cursor.fetchone()
if existing_survey is None:
# Insert the survey_id into the survey_status table
cursor.execute(
"INSERT INTO survey_status (survey_id, user_id, status) VALUES (%s, %s, %s)",
(survey_id, user_id, 'active')
)
conn.commit()
cursor.close()
return user_id
def get_answered_questions_count(conn, user_id):
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM survey_responses WHERE user_id = %s", (user_id,))
answered_count = cursor.fetchone()[0]
cursor.close()
return answered_count
def mark_question_as_answered(conn, user_id, audio_index, natural, intelligibility, speed, time_spent, comment, survey_id):
cursor = conn.cursor()
# Adjust feedback values to start from 1 instead of 0
natural += 1
intelligibility += 1
speed += 1
# Get the current max response_id
cursor.execute('SELECT COALESCE(MAX(response_id), 0) FROM survey_responses')
max_response_id = cursor.fetchone()[0]
new_response_id = max_response_id + 1
# Insert the answers into the survey_responses table with the time_spent and comment
sound_name = f"sound_{audio_index + 1}"
cursor.execute('''
INSERT INTO survey_responses (response_id, survey_id, user_id, sound_name, d, a, h, time_spent, comment)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
''', (new_response_id, survey_id, user_id, sound_name, natural, intelligibility, speed, time_spent, comment))
conn.commit()
cursor.close()
def is_question_answered(conn, user_id, audio_index, survey_id):
cursor = conn.cursor()
sound_name = f"sound_{audio_index + 1}"
cursor.execute('''
SELECT 1 FROM survey_responses
WHERE user_id = %s AND sound_name = %s AND survey_id = %s
''', (user_id, sound_name, survey_id))
result = cursor.fetchone()
cursor.close()
return result is not None