Sa-m commited on
Commit
6adb0a0
·
verified ·
1 Parent(s): 26c10bd

Update login_module/chat.py

Browse files
Files changed (1) hide show
  1. login_module/chat.py +81 -49
login_module/chat.py CHANGED
@@ -9,25 +9,23 @@ from dotenv import load_dotenv
9
  # Load environment variables
10
  load_dotenv()
11
 
12
- # Configure Generative AI
 
13
  genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
14
- text_model = genai.GenerativeModel("gemini-2.5-flash")
 
 
15
 
16
 
17
- def file_processing_chat(pdf_file_obj): # Take the Gradio file object
18
- """Processes the uploaded PDF file for the chat module."""
19
- if not pdf_file_obj:
20
- print("No file object provided to file_processing_chat.")
21
  return ""
22
 
23
  try:
24
- # --- Key Fix: Extract the file path correctly ---
25
- if hasattr(pdf_file_obj, 'name'):
26
- file_path = pdf_file_obj.name
27
- else:
28
- file_path = str(pdf_file_obj)
29
- print(f"File object does not have 'name' attribute. Using str(): {file_path}")
30
-
31
  print(f"Attempting to process file at path: {file_path}")
32
 
33
  # --- Use the file path with PyPDF2 ---
@@ -46,10 +44,11 @@ def file_processing_chat(pdf_file_obj): # Take the Gradio file object
46
  print(error_msg)
47
  return ""
48
  except Exception as e:
49
- error_msg = f"Unexpected error processing PDF from object {pdf_file_obj}: {e}"
50
  print(error_msg)
51
  return ""
52
 
 
53
  def getallinfo_chat(data):
54
  """Formats resume data."""
55
  if not data or not data.strip():
@@ -59,6 +58,7 @@ def getallinfo_chat(data):
59
  education, skills of the user like in a resume. If the details are not provided return: not a resume.
60
  If details are provided then please try again and format the whole in a single paragraph covering all the information. """
61
  try:
 
62
  response = text_model.generate_content(text)
63
  response.resolve()
64
  return response.text
@@ -66,6 +66,7 @@ def getallinfo_chat(data):
66
  print(f"Error formatting resume data: {e}")
67
  return "Error processing resume data."
68
 
 
69
  def get_answer(question, input_text):
70
  """Generates answer/suggestions based on the question and resume text."""
71
  # Handle empty inputs
@@ -80,6 +81,7 @@ def get_answer(question, input_text):
80
  it should be less and precise. dont tell the user to change the whole resume. just give them some suggestions. dont give
81
  bullet points. Be point to point with user."""
82
  try:
 
83
  response = text_model.generate_content(text)
84
  response.resolve()
85
  return response.text
@@ -87,68 +89,98 @@ def get_answer(question, input_text):
87
  print(f"Error generating answer: {e}")
88
  return "Sorry, I couldn't generate an answer at the moment."
89
 
 
90
  # --- Gradio Chat Interface Functions ---
91
 
92
  def process_resume_chat(file_obj):
93
  """Handles resume upload and initial processing for chat."""
 
94
  if not file_obj:
95
- return "Please upload a PDF resume.", "", gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
 
 
 
 
 
 
 
96
 
97
  try:
98
- # Save uploaded file to a temporary location
99
- temp_dir = tempfile.mkdtemp()
100
- file_path = os.path.join(temp_dir, file_obj.name)
101
- with open(file_path, "wb") as f:
102
- f.write(file_obj.read())
103
-
104
- # Process the PDF
105
- raw_text = file_processing_chat(file_path)
106
- if not raw_text.strip():
107
- os.remove(file_path)
108
- os.rmdir(temp_dir)
109
- return "Could not extract text from the PDF.", "", gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
110
-
111
- processed_data = getallinfo_chat(raw_text)
112
-
113
- # Clean up temporary file
114
- os.remove(file_path)
115
- os.rmdir(temp_dir)
116
-
 
 
 
 
 
 
 
 
 
 
 
 
117
  return (
118
  f"Resume processed successfully!",
119
- processed_data, # Pass processed data for chat
120
- gr.update(visible=True), # Show chat input
121
- gr.update(visible=True), # Show send button
122
- [] # Clear previous chat history (return empty list for Chatbot)
123
  )
124
  except Exception as e:
125
  error_msg = f"Error processing file: {str(e)}"
126
- print(error_msg)
127
- return error_msg, "", gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
 
 
 
 
 
 
 
 
 
128
 
129
  def chat_with_resume(query, resume_data, history):
130
  """Handles the chat interaction."""
131
  # history is automatically managed by Gradio Chatbot, we just need to append to it
 
 
 
 
132
  if not query or not query.strip() or not resume_data or not resume_data.strip():
133
- # Return existing history if inputs are missing or empty
134
- # Gradio Chatbot expects a list of tuples [(user_msg, bot_response), ...]
135
- # If history is None, initialize as empty list
136
- current_history = history if history is not None else []
137
- # Add the error message to the chat history
138
  current_history.append((query if query else "", "Please enter a question and ensure your resume is processed."))
139
  return "", current_history # Clear input, update history
140
 
141
  try:
142
  answer = get_answer(query, resume_data)
143
- # Update history
144
- # Gradio Chatbot expects a list of tuples [(user_msg, bot_response), ...]
145
- current_history = history if history is not None else []
146
  current_history.append((query, answer))
147
  return "", current_history # Clear input, update history
148
  except Exception as e:
149
  error_msg = f"Error during chat: {str(e)}"
150
  print(error_msg)
151
- current_history = history if history is not None else []
152
  current_history.append((query, error_msg))
153
  return "", current_history
154
 
 
 
 
 
9
  # Load environment variables
10
  load_dotenv()
11
 
12
+ # Configure Generative AI (Ensure model name is correct)
13
+ # Note: 'gemini-2.5-flash' might need verification. Common ones are 'gemini-1.5-flash', 'gemini-pro'.
14
  genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
15
+ text_model = genai.GenerativeModel("gemini-2.5-flash") # Potentially incorrect model name
16
+ # text_model = genai.GenerativeModel("gemini-1.5-flash") # Using a known model name
17
+ # print("Using Generative AI model for chat: gemini-1.5-flash")
18
 
19
 
20
+ def file_processing_chat(pdf_file_path_string): # Expect the file path string directly
21
+ """Processes the uploaded PDF file given its path."""
22
+ if not pdf_file_path_string:
23
+ print("No file path provided to file_processing_chat.")
24
  return ""
25
 
26
  try:
27
+ # Ensure the input is treated as a string path
28
+ file_path = str(pdf_file_path_string)
 
 
 
 
 
29
  print(f"Attempting to process file at path: {file_path}")
30
 
31
  # --- Use the file path with PyPDF2 ---
 
44
  print(error_msg)
45
  return ""
46
  except Exception as e:
47
+ error_msg = f"Unexpected error processing PDF from path {pdf_file_path_string}: {e}"
48
  print(error_msg)
49
  return ""
50
 
51
+
52
  def getallinfo_chat(data):
53
  """Formats resume data."""
54
  if not data or not data.strip():
 
58
  education, skills of the user like in a resume. If the details are not provided return: not a resume.
59
  If details are provided then please try again and format the whole in a single paragraph covering all the information. """
60
  try:
61
+ # Use the correct model instance
62
  response = text_model.generate_content(text)
63
  response.resolve()
64
  return response.text
 
66
  print(f"Error formatting resume data: {e}")
67
  return "Error processing resume data."
68
 
69
+
70
  def get_answer(question, input_text):
71
  """Generates answer/suggestions based on the question and resume text."""
72
  # Handle empty inputs
 
81
  it should be less and precise. dont tell the user to change the whole resume. just give them some suggestions. dont give
82
  bullet points. Be point to point with user."""
83
  try:
84
+ # Use the correct model instance
85
  response = text_model.generate_content(text)
86
  response.resolve()
87
  return response.text
 
89
  print(f"Error generating answer: {e}")
90
  return "Sorry, I couldn't generate an answer at the moment."
91
 
92
+
93
  # --- Gradio Chat Interface Functions ---
94
 
95
  def process_resume_chat(file_obj):
96
  """Handles resume upload and initial processing for chat."""
97
+ print(f"process_resume_chat called with: {file_obj}") # Debug print
98
  if not file_obj:
99
+ print("No file uploaded in process_resume_chat.")
100
+ return (
101
+ "Please upload a PDF resume.",
102
+ "",
103
+ gr.update(visible=False),
104
+ gr.update(visible=False),
105
+ gr.update(visible=False)
106
+ )
107
 
108
  try:
109
+ # --- Correctly handle the file path from Gradio ---
110
+ # Determine the correct file path from the Gradio object
111
+ if hasattr(file_obj, 'name'):
112
+ # This is the standard way for Gradio File uploads
113
+ uploaded_file_path = file_obj.name
114
+ print(f"Using Gradio-provided file path: {uploaded_file_path}")
115
+ else:
116
+ # Fallback: If it's already a string path (less common) or different structure
117
+ uploaded_file_path = str(file_obj)
118
+ print(f"File object does not have 'name' attribute. Using str(): {uploaded_file_path}")
119
+
120
+ # --- Process the PDF directly from the uploaded file path ---
121
+ # No need to save it again, we can use the path Gradio provided
122
+ raw_text = file_processing_chat(uploaded_file_path) # Pass the path string
123
+ print(f"Raw text extracted (length: {len(raw_text) if raw_text else 0})")
124
+
125
+ if not raw_text or not raw_text.strip():
126
+ print("Failed to extract text or text is empty in process_resume_chat.")
127
+ return (
128
+ "Could not extract text from the PDF.",
129
+ "",
130
+ gr.update(visible=False),
131
+ gr.update(visible=False),
132
+ gr.update(visible=False)
133
+ )
134
+
135
+ # --- Format the resume data ---
136
+ processed_data = getallinfo_chat(raw_text) # Use the new model instance if corrected
137
+ print(f"Resume processed for chat (length: {len(processed_data) if processed_data else 0})")
138
+
139
+ # --- Return success state and values ---
140
  return (
141
  f"Resume processed successfully!",
142
+ processed_data, # Pass processed data for chat
143
+ gr.update(visible=True), # Show chat input
144
+ gr.update(visible=True), # Show send button
145
+ [] # Clear/initialize chat history
146
  )
147
  except Exception as e:
148
  error_msg = f"Error processing file: {str(e)}"
149
+ print(f"Exception in process_resume_chat: {error_msg}")
150
+ import traceback
151
+ traceback.print_exc() # Print full traceback for debugging
152
+ return (
153
+ error_msg,
154
+ "",
155
+ gr.update(visible=False),
156
+ gr.update(visible=False),
157
+ gr.update(visible=False)
158
+ )
159
+
160
 
161
  def chat_with_resume(query, resume_data, history):
162
  """Handles the chat interaction."""
163
  # history is automatically managed by Gradio Chatbot, we just need to append to it
164
+ # Gradio Chatbot expects a list of tuples [(user_msg, bot_response), ...]
165
+ # If history is None, initialize as empty list
166
+ current_history = history if history is not None else []
167
+
168
  if not query or not query.strip() or not resume_data or not resume_data.strip():
169
+ # Add an error message to the chat history if inputs are missing or empty
 
 
 
 
170
  current_history.append((query if query else "", "Please enter a question and ensure your resume is processed."))
171
  return "", current_history # Clear input, update history
172
 
173
  try:
174
  answer = get_answer(query, resume_data)
175
+ # Append the valid Q&A to the history
 
 
176
  current_history.append((query, answer))
177
  return "", current_history # Clear input, update history
178
  except Exception as e:
179
  error_msg = f"Error during chat: {str(e)}"
180
  print(error_msg)
 
181
  current_history.append((query, error_msg))
182
  return "", current_history
183
 
184
+
185
+ # Print statement to confirm module load (optional)
186
+ print("Chat module loaded successfully.")