Spaces:
Build error
Build error
File size: 2,829 Bytes
d90493e | 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 | import psycopg2
from dotenv import load_dotenv
from datetime import timedelta
load_dotenv()
def get_survey_and_user_id(conn, user_id):
cursor = conn.cursor()
cursor.execute('''
SELECT survey_id, user_id FROM survey_status WHERE user_id = %s
''', (user_id,))
result = cursor.fetchone()
cursor.close()
return result
def is_question_answered(conn, user_id, sound_name):
cursor = conn.cursor()
cursor.execute('''
SELECT 1 FROM survey_responses WHERE user_id = %s AND sound_name = %s
''', (user_id, sound_name))
result = cursor.fetchone()
cursor.close()
return result is not None
def get_time_spent(conn, user_id, sound_name):
cursor = conn.cursor()
cursor.execute('''
SELECT time_spent FROM survey_responses WHERE user_id = %s AND sound_name = %s
''', (user_id, sound_name))
result = cursor.fetchone()
cursor.close()
return result[0] if result else None
def format_time_spent(time_spent):
total_seconds = time_spent.total_seconds()
minutes = int(total_seconds // 60)
seconds = total_seconds % 60
return f"{minutes} mins {seconds:.2f} secs"
def insert_time_spent(conn, user_id, survey_id, sound_name, time_spent):
cursor = conn.cursor()
formatted_time_spent = format_time_spent(time_spent)
try:
cursor.execute('''
INSERT INTO survey_timers (user_id, survey_id, sound_table_name, response_id, time_spent)
VALUES (%s, %s, %s, (SELECT COALESCE(MAX(response_id), 0) + 1 FROM survey_timers), %s)
''', (user_id, survey_id, sound_name, formatted_time_spent))
conn.commit()
except psycopg2.errors.UniqueViolation:
conn.rollback()
finally:
cursor.close()
def get_user_login_time(conn, user_id):
cursor = conn.cursor()
cursor.execute('''
SELECT login_time FROM users WHERE user_id = %s
''', (user_id,))
result = cursor.fetchone()
cursor.close()
return result[0] if result else None
def calculate_time_spent(conn, user_id):
result = get_survey_and_user_id(conn, user_id)
if result is None:
return
survey_id, user_id = result
sound_names = [f'sound_{i+1}' for i in range(27)] # Assuming 27 sounds
previous_time_spent = get_user_login_time(conn, user_id)
for sound_name in sound_names:
if is_question_answered(conn, user_id, sound_name):
current_time_spent = get_time_spent(conn, user_id, sound_name)
if previous_time_spent is not None:
time_spent_difference = current_time_spent - previous_time_spent
insert_time_spent(conn, user_id, survey_id, sound_name, time_spent_difference)
previous_time_spent = current_time_spent |