File size: 3,655 Bytes
37faa13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2c4299
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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