Sa-m commited on
Commit
8bb6bd2
·
verified ·
1 Parent(s): 972f7fd

Update interview_history.py

Browse files
Files changed (1) hide show
  1. interview_history.py +67 -68
interview_history.py CHANGED
@@ -1,4 +1,6 @@
1
  # PrepGenie/interview_history.py
 
 
2
  import firebase_admin
3
  from firebase_admin import firestore
4
  import datetime
@@ -8,116 +10,113 @@ import json
8
  # Assumes Firebase Admin is initialized in app.py
9
  try:
10
  db = firestore.client()
11
- print("Firestore client for history initialized successfully.")
12
  FIRESTORE_AVAILABLE = True
13
  except Exception as e:
14
- print(f"Error initializing Firestore client for history: {e}")
15
  db = None
16
  FIRESTORE_AVAILABLE = False
17
 
18
  def save_interview_history(user_id, interview_data):
19
  """
20
  Saves the mock interview results to Firestore under the user's document.
21
-
22
- Args:
23
- user_id (str): The unique ID of the logged-in user (from Firebase Auth).
24
- interview_data (dict): A dictionary containing interview details.
25
- Expected structure:
26
- {
27
- "timestamp": str (ISO format datetime),
28
- "resume_overview": str,
29
- "selected_roles": list,
30
- "questions": list,
31
- "answers": list,
32
- "feedback": list,
33
- "interactions": dict,
34
- "metrics_list": list,
35
- "final_metrics": dict,
36
- "average_rating": float,
37
- "evaluation_report": str,
38
- # ... other relevant data ...
39
- }
40
-
41
- Returns:
42
- bool: True if successful, False otherwise.
43
  """
44
  if not FIRESTORE_AVAILABLE or not db:
45
- print("Firestore client not available. Cannot save history.")
46
  return False
47
  if not user_id:
48
- print("User ID is required to save history.")
49
  return False
50
 
51
  try:
52
- # Reference to the user's document in the 'users' collection
53
  user_ref = db.collection('users').document(user_id)
54
-
55
- # Add the interview data to a subcollection 'interview_history'
56
  history_ref = user_ref.collection('interview_history')
57
-
58
- # Add the data with an auto-generated ID
59
  history_ref.add(interview_data)
60
-
61
- print(f"Interview history saved for user {user_id}")
62
  return True
63
  except Exception as e:
64
- print(f"Error saving interview history for user {user_id}: {e}")
65
  return False
66
 
67
  def load_interview_history(user_id, limit=5):
68
  """
69
  Loads the mock interview history for a specific user from Firestore.
70
-
71
- Args:
72
- user_id (str): The unique ID of the logged-in user.
73
- limit (int): The maximum number of recent interviews to retrieve.
74
-
75
- Returns:
76
- list: A list of dictionaries, each representing an interview record.
77
- Returns an empty list if no history is found or on error.
78
  """
79
  if not FIRESTORE_AVAILABLE or not db:
80
- print("Firestore client not available. Cannot load history.")
81
  return []
82
  if not user_id:
83
- print("User ID is required to load history.")
84
  return []
85
 
86
  try:
87
- # Reference to the user's interview history subcollection
88
  history_ref = db.collection('users').document(user_id).collection('interview_history')
89
-
90
- # Query the history, ordered by timestamp descending (most recent first), limited
91
  docs = history_ref.order_by('timestamp', direction=firestore.Query.DESCENDING).limit(limit).stream()
92
 
93
  history_list = []
94
  for doc in docs:
95
- # Convert Firestore document to dictionary
96
  interview_record = doc.to_dict()
97
- # Add the document ID if needed (optional)
98
- # interview_record['doc_id'] = doc.id
99
  history_list.append(interview_record)
100
 
101
- print(f"Loaded {len(history_list)} interview records for user {user_id}")
102
  return history_list
103
  except Exception as e:
104
- print(f"Error loading interview history for user {user_id}: {e}")
105
  return []
106
 
107
- # Example usage (for testing or understanding structure):
108
- # Assuming you have a user ID and interview data after an interview session:
109
- # user_uid = "some_user_id_from_firebase_auth"
110
- # interview_summary_data = {
111
- # "timestamp": datetime.datetime.now().isoformat(),
112
- # "resume_overview": "Overview of the resume...",
113
- # "selected_roles": ["Software Engineer"],
114
- # "questions": ["Question 1?", "Question 2?"],
115
- # "answers": ["Answer 1", "Answer 2"],
116
- # "feedback": ["Feedback 1", "Feedback 2"],
117
- # # ... other fields ...
118
- # }
119
- # save_interview_history(user_uid, interview_summary_data)
120
 
121
- # Load last 3 interviews
122
- # past_interviews = load_interview_history(user_uid, limit=3)
123
- # print(past_interviews)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # PrepGenie/interview_history.py
2
+ """Handles saving and loading interview history to/from Firestore."""
3
+
4
  import firebase_admin
5
  from firebase_admin import firestore
6
  import datetime
 
10
  # Assumes Firebase Admin is initialized in app.py
11
  try:
12
  db = firestore.client()
13
+ print("Firestore client for history initialized successfully in interview_history.")
14
  FIRESTORE_AVAILABLE = True
15
  except Exception as e:
16
+ print(f"Error initializing Firestore client for history in interview_history: {e}")
17
  db = None
18
  FIRESTORE_AVAILABLE = False
19
 
20
  def save_interview_history(user_id, interview_data):
21
  """
22
  Saves the mock interview results to Firestore under the user's document.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
  if not FIRESTORE_AVAILABLE or not db:
25
+ print("Firestore client not available in interview_history. Cannot save history.")
26
  return False
27
  if not user_id:
28
+ print("User ID is required in interview_history to save history.")
29
  return False
30
 
31
  try:
 
32
  user_ref = db.collection('users').document(user_id)
 
 
33
  history_ref = user_ref.collection('interview_history')
 
 
34
  history_ref.add(interview_data)
35
+ print(f"Interview history saved for user {user_id} in interview_history")
 
36
  return True
37
  except Exception as e:
38
+ print(f"Error saving interview history for user {user_id} in interview_history: {e}")
39
  return False
40
 
41
  def load_interview_history(user_id, limit=5):
42
  """
43
  Loads the mock interview history for a specific user from Firestore.
 
 
 
 
 
 
 
 
44
  """
45
  if not FIRESTORE_AVAILABLE or not db:
46
+ print("Firestore client not available in interview_history. Cannot load history.")
47
  return []
48
  if not user_id:
49
+ print("User ID is required in interview_history to load history.")
50
  return []
51
 
52
  try:
 
53
  history_ref = db.collection('users').document(user_id).collection('interview_history')
 
 
54
  docs = history_ref.order_by('timestamp', direction=firestore.Query.DESCENDING).limit(limit).stream()
55
 
56
  history_list = []
57
  for doc in docs:
 
58
  interview_record = doc.to_dict()
 
 
59
  history_list.append(interview_record)
60
 
61
+ print(f"Loaded {len(history_list)} interview records for user {user_id} in interview_history")
62
  return history_list
63
  except Exception as e:
64
+ print(f"Error loading interview history for user {user_id} in interview_history: {e}")
65
  return []
66
 
67
+ # --- History Loading Function for UI ---
68
+ def load_user_history(user_id_state):
69
+ """Function to load and format interview history for display in the UI."""
70
+ if not FIRESTORE_AVAILABLE:
71
+ return "History feature is not available (Firestore not initialized)."
72
+ if not user_id_state:
73
+ return "Please log in to view your interview history."
 
 
 
 
 
 
74
 
75
+ try:
76
+ history_list = load_interview_history(user_id_state, limit=5)
77
+
78
+ if not history_list:
79
+ return "No interview history found."
80
+
81
+ output_text = "**Your Recent Mock Interviews:**\n\n"
82
+ for idx, record in enumerate(history_list):
83
+ timestamp = record.get('timestamp', 'Unknown Time')
84
+ try:
85
+ if 'Z' in timestamp:
86
+ dt = datetime.datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
87
+ else:
88
+ dt = datetime.datetime.fromisoformat(timestamp)
89
+ formatted_time = dt.strftime("%Y-%m-%d %H:%M:%S")
90
+ except Exception as e:
91
+ print(f"Error parsing timestamp {timestamp} in load_user_history: {e}")
92
+ formatted_time = timestamp
93
+
94
+ roles = ", ".join(record.get('selected_roles', ['N/A']))
95
+ avg_rating = record.get('average_rating', 'N/A')
96
+ output_text += f"--- **Interview #{len(history_list) - idx} ({formatted_time})** ---\n"
97
+ output_text += f"**Roles Applied:** {roles}\n"
98
+ output_text += f"**Average Rating:** {avg_rating:.2f}\n\n"
99
+
100
+ interactions = record.get('interactions', {})
101
+ if interactions:
102
+ output_text += "**Interview Snippets:**\n"
103
+ count = 0
104
+ for q_key, a_val in list(interactions.items())[:3]:
105
+ q_display = q_key.split(':', 1)[1].strip() if ':' in q_key else q_key
106
+ a_display = a_val.split(':', 1)[1].strip() if ':' in a_val else a_val
107
+ output_text += f"- **Q:** {q_display[:100]}{'...' if len(q_display) > 100 else ''}\n"
108
+ output_text += f" **A:** {a_display[:100]}{'...' if len(a_display) > 100 else ''}\n"
109
+ count += 1
110
+ if count >= 3:
111
+ break
112
+ if len(interactions) > 3:
113
+ output_text += f"... (and {len(interactions) - 3} more questions)\n"
114
+ else:
115
+ output_text += "**Details:** Not available.\n"
116
+ output_text += "\n---\n\n"
117
+
118
+ return output_text
119
+ except Exception as e:
120
+ error_msg = f"Error loading interview history in load_user_history: {str(e)}"
121
+ print(error_msg)
122
+ return error_msg