markfu0213 commited on
Commit
b3f6ab1
·
verified ·
1 Parent(s): f2d8f32
Files changed (1) hide show
  1. Resume_Refiner.py +392 -0
Resume_Refiner.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import gradio as gr
3
+ import PyPDF2
4
+ import docx
5
+ from docx import Document
6
+ from gradio import CSVLogger
7
+ import os
8
+ from reportlab.lib.pagesizes import letter
9
+ from reportlab.pdfgen import canvas
10
+ from reportlab.lib.styles import getSampleStyleSheet
11
+ from reportlab.platypus import Paragraph
12
+ from reportlab.lib.units import inch
13
+ from reportlab.lib.pagesizes import letter
14
+ from reportlab.pdfgen import canvas
15
+
16
+ from docx import Document
17
+ from docx.shared import Pt
18
+
19
+ from docx.enum.text import WD_UNDERLINE
20
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
21
+
22
+ from docx.shared import RGBColor
23
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
24
+ from docx.oxml import parse_xml
25
+ from docx.oxml.ns import nsdecls
26
+
27
+
28
+
29
+ openai.api_key = "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"
30
+
31
+ messages = []
32
+
33
+
34
+ latest_resume_text = ""
35
+ desired_position = ""
36
+ default_text_1 = "Hello, I will share a candidate's resume with you. Please provide a summary for me"
37
+
38
+ default_text_2 = "Hello, I will share a candidate's resume with you. Please desensitize the resume by removing or redacting any personal contact information like the phone number, home address, and email address. Also remove or mask any private details like ID numbers, exact dates for education and work history, and compensation details. Double check that no other private information is included. The goal is to remove personally identifying details while still allowing this candidate's professional qualifications to be visible to potential employers."
39
+
40
+ default_text_3 = "请帮我阅读候选人简历并总结出以下几个部分。第一个板块是“个人信息”,请总结出此后选人的姓名,性别,工作经验(多少年),最高学历,毕业院校,专业,和毕业时间。第二个部分是此候选人的本人评价,放进一个自然段里。第三个部分是具体得工作经历。第四个部分是做过的项目经验。请根据你对于这位候选人简历的最细致的阅读排出以上几个部分。每个部分由自己的标题:五个标题为 个人信息,本人评价,工作经历,和项目经验。请把每一个小项写得细致一点,并且用数字排序!"
41
+
42
+
43
+ def set_text_1():
44
+ return default_text_1
45
+ def set_text_2():
46
+ return default_text_2
47
+ def set_text_3():
48
+ return default_text_3
49
+
50
+ # # extracting text from pdf
51
+ # def extract_text_from_pdf(file):
52
+ # reader = PyPDF2.PdfReader(file)
53
+ # text = ""
54
+ # for page in reader.pages:
55
+ # text += page.extract_text()
56
+ # return text
57
+
58
+
59
+ #write a function that extract text from a pdf that could contain multiple pages
60
+ def extract_text_from_pdf(file):
61
+ reader = PyPDF2.PdfReader(file)
62
+ text = ""
63
+ for page in reader.pages:
64
+ text += page.extract_text()
65
+ return text
66
+
67
+ # extracting text from doc
68
+ def extract_text_from_docx(file):
69
+
70
+ doc = docx.Document(file)
71
+ all_text = []
72
+
73
+ for para in doc.paragraphs:
74
+ # Extract the text from the current paragraph
75
+ paragraph_text = para.text
76
+ all_text.append(paragraph_text)
77
+
78
+ combined_text = " ".join(all_text)
79
+ return combined_text
80
+
81
+ def handle_file_upload(uploaded_files):
82
+ combined_text = ""
83
+ if uploaded_files is None:
84
+ return ""
85
+ for uploaded_file in uploaded_files:
86
+ file_type = uploaded_file.name.split('.')[-1].lower()
87
+ if file_type == 'pdf':
88
+ combined_text += extract_text_from_pdf(uploaded_file)
89
+ elif file_type in ['docx', 'doc']:
90
+ combined_text += extract_text_from_docx(uploaded_file)
91
+ else:
92
+ combined_text += "Unsupported file format, please upload a PDF or Word document.\n"
93
+ return combined_text
94
+
95
+
96
+ def clear_inputs():
97
+ messages = []
98
+ return "", None
99
+
100
+ def log_conversation(input, reply):
101
+ with open("log.csv", "a") as log_file:
102
+ log_file.write(f"user_input: {input},\n\n Chatgpt: {reply}\n\n")
103
+
104
+
105
+ import re
106
+ from docx import Document
107
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
108
+ from docx.shared import RGBColor
109
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
110
+
111
+
112
+ def is_chinese_char(char):
113
+ """Check if a given character is a Chinese character."""
114
+ return '\u4e00' <= char <= '\u9fff'
115
+
116
+ def count_chinese_chars(text):
117
+ """Count the number of Chinese characters in a string."""
118
+ return sum(is_chinese_char(char) for char in text)
119
+
120
+
121
+ def generate_resume_document(latest_resume_text):
122
+ # Define keywords that indicate the start of a new section
123
+ section_keywords = ["个人信息", "本人评价", "工作经历", "项目经验"]
124
+
125
+ # Create a new Document
126
+ doc = Document()
127
+
128
+ # Add a title to the document
129
+ heading = doc.add_heading('候选人简历', level=0)
130
+ run = heading.add_run()
131
+ run.underline = WD_UNDERLINE.SINGLE
132
+
133
+ # Center-align the heading
134
+ paragraph_format = heading.paragraph_format
135
+ paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
136
+
137
+ # Check if the text is empty
138
+ if not latest_resume_text.strip():
139
+ doc.add_paragraph("No resume text found")
140
+ return None
141
+
142
+ # Remove non-word characters from the text except for spaces and new lines
143
+ # Remove non-word characters from the text except for "-", ",", "." and numbers
144
+
145
+ cleaned_text = re.sub(r'[^\w\s\-\,\.\d]', '', latest_resume_text)
146
+
147
+
148
+ # Split the resume text into lines
149
+ lines = cleaned_text.split('\n')
150
+
151
+ # Variables to store the current section title and its content
152
+ current_section = None
153
+ current_content = []
154
+
155
+ # Function to add a section to the document with bullet points
156
+ def add_section_to_doc(section, content):
157
+ global name
158
+ if section and content:
159
+ sec = doc.add_heading(section, level=0)
160
+ for run in sec.runs:
161
+ run.font.size = Pt(14)
162
+
163
+
164
+
165
+ if section == "个人信息":
166
+ # Combine all content lines into a single line separated by a semicolon
167
+ combined_content = ';'.join(content)
168
+ p = doc.add_paragraph() # Create a new paragraph for combined content
169
+
170
+ last_index = 0 # Keep track of the last index processed
171
+ for keyword in ["姓名", "性别", "工作经验", "最高学历", "毕业院校", "专业", "毕业时间"]:
172
+ if keyword in combined_content:
173
+ start_index = combined_content.index(keyword, last_index)
174
+
175
+ # Add text before the keyword as a normal run
176
+ p.add_run(combined_content[last_index:start_index])
177
+
178
+ # Add the keyword and the colon as a bold run
179
+ bold_run = p.add_run(keyword + ':')
180
+ bold_run.bold = True
181
+
182
+ # Update the last index processed
183
+ last_index = start_index + len(keyword)
184
+
185
+ if keyword == "姓名":
186
+ name_start_index = last_index
187
+ try:
188
+ # Try to find the start index of the next keyword "性别"
189
+ name_end_index = combined_content.index("性别", name_start_index)
190
+ # Store the content into name variable
191
+ name = combined_content[name_start_index:name_end_index]
192
+ # Remove any non-Chinese characters
193
+ name = re.sub(r'[^\u4e00-\u9fff]', '', name)
194
+ except ValueError:
195
+ # Handle the case where "性别" is not found
196
+ name = "需手动填写"
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+ # Add any remaining text after the last keyword
205
+ p.add_run(combined_content[last_index:])
206
+
207
+
208
+
209
+
210
+ else:
211
+ for line in content:
212
+ # # Count Chinese characters in the line
213
+ # chinese_char_count = count_chinese_chars(line)
214
+ # if chinese_char_count < 5:
215
+ # doc.add_heading(line, level=0)
216
+ # p = doc.add_paragraph()
217
+ # p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
218
+ # for run in sec.runs:
219
+ # run.font.size = Pt(14)
220
+
221
+ # else:
222
+
223
+ doc.add_paragraph(line)
224
+
225
+
226
+
227
+ for line in lines:
228
+ # Check for section titles (considering case-insensitivity)
229
+ if any(line.strip().upper() == keyword for keyword in section_keywords):
230
+ # Add the previous section to the document before starting a new one
231
+ add_section_to_doc(current_section, current_content)
232
+
233
+
234
+
235
+
236
+ current_section = line.strip().title() # Title Case for headings
237
+ current_content = []
238
+ else:
239
+ # Clean line and add to current content
240
+ clean_line = line.strip()
241
+ if clean_line: # Ignore empty lines
242
+ # Append clean_line to current_content, removing any additional internal line breaks
243
+ current_content.append(re.sub(r'\s+', ' ', clean_line))
244
+
245
+ # Add the last section to the document
246
+ add_section_to_doc(current_section, current_content)
247
+
248
+ # Save the document
249
+ word_filename = "博网科技-" + name + "-" + desired_position + ".docx"
250
+ doc.save(word_filename)
251
+ return word_filename
252
+
253
+
254
+
255
+
256
+
257
+ def CustomChatGPT(user_input, uploaded_file):
258
+ global messages, latest_resume_text, desired_position, name # Declare latest_resume_text as global if it's used globally
259
+ resume_text = ""
260
+ resume_text = handle_file_upload(uploaded_file)
261
+ print("Resume text from the file:", resume_text)
262
+
263
+ if resume_text:
264
+ messages.append({"role": "system", "content": resume_text})
265
+ # if the resume text contains "期望职位", extract the desired position and store it in desired_position
266
+ if "期望职位" in resume_text:
267
+ match = re.search(r'期望职位:(.+?)\s', resume_text)
268
+ if match:
269
+ desired_position = match.group(1)
270
+ # Remove non-Chinese characters
271
+ desired_position = re.sub(r'[^\u4e00-\u9fff]', '', desired_position)
272
+ else:
273
+ desired_position = "需手动填写"
274
+
275
+
276
+
277
+ messages.append({"role": "user", "content": user_input})
278
+ response = openai.ChatCompletion.create(
279
+ model="gpt-3.5-turbo",
280
+ messages=messages
281
+ )
282
+ ChatGPT_reply = response.choices[0].message.content
283
+ messages.append({"role": "assistant", "content": ChatGPT_reply})
284
+
285
+ combined_input = user_input + " " + resume_text
286
+ log_conversation(combined_input, ChatGPT_reply)
287
+
288
+ latest_resume_text = ChatGPT_reply
289
+
290
+ if "请帮我阅读候选人简历" in user_input:
291
+ word_filename = generate_resume_document(latest_resume_text)
292
+ ChatGPT_reply = "Resume generated successfully. Please download the file using the link below."
293
+ messages = []
294
+ else:
295
+ doc = Document()
296
+ doc.add_paragraph(ChatGPT_reply)
297
+ word_filename = "generated_response.docx"
298
+ doc.save(word_filename)
299
+ # reset the messages to start a new conversation
300
+ messages = []
301
+
302
+ return ChatGPT_reply, word_filename
303
+
304
+
305
+
306
+ def get_log_file():
307
+ return "log.csv"
308
+ def read_log_file():
309
+ if os.path.exists("log.csv"):
310
+ with open("log.csv", "r") as file:
311
+ return file.read()
312
+ else:
313
+ return "Log file is empty or doesn't exist."
314
+ def clear_log_file():
315
+ if not os.path.exists("log.csv"):
316
+ return "file not exist"
317
+ else:
318
+ with open("log.csv", "w") as log_file:
319
+ log_file.write("")
320
+ return "Log cleared"
321
+
322
+ def main():
323
+ custom_css = """
324
+ <style>
325
+ .custom-button .mdc-button {
326
+ background-color: #90EE90; /* Light Green */
327
+ color: black;
328
+ border: none;
329
+ border-radius: 6px;
330
+ padding: 10px 20px;
331
+ margin: 8px 0;
332
+ cursor: pointer;
333
+ font-size: 14px;
334
+ text-align: center;
335
+ }
336
+ .custom-button .mdc-button:hover {
337
+ background-color: #76b476; /* Darker shade for hover effect */
338
+ }
339
+ </style>
340
+ """
341
+
342
+ with gr.Blocks(css=custom_css) as demo:
343
+ gr.Markdown("# Resume Analysis Tool", elem_classes=["centered-title"])
344
+
345
+ with gr.Row():
346
+ with gr.Column():
347
+ text_input = gr.Textbox()
348
+ file_input = gr.File(file_count="multiple", label="Upload Resume")
349
+
350
+ with gr.Row():
351
+ btn1 = gr.Button("Summary", elem_classes=["custom-button"])
352
+ btn2 = gr.Button("Desensitization", elem_classes=["custom-button"])
353
+ btn3 = gr.Button("简历生成", elem_classes=["custom-button"])
354
+
355
+
356
+ btn1.click(fn=set_text_1, inputs=[], outputs=text_input)
357
+ btn2.click(fn=set_text_2, inputs=[], outputs=text_input)
358
+ btn3.click(fn=set_text_3, inputs=[], outputs=text_input)
359
+
360
+
361
+ with gr.Row():
362
+ submit_btn = gr.Button("Submit", elem_classes=["custom-button"])
363
+ clear_btn = gr.Button("Clear", elem_classes=["custom-button"])
364
+ clear_btn.click(fn=clear_inputs, inputs=[], outputs=[])
365
+
366
+ with gr.Column():
367
+ with gr.Row():
368
+ output_text = gr.Textbox(label="ChatGPT Reply", interactive=True, lines=1)
369
+ with gr.Row():
370
+ output_word = gr.File(label="Download Word File")
371
+ # output_pdf = gr.File(label="Download PDF File")
372
+
373
+ submit_btn.click(fn=CustomChatGPT, inputs=[text_input, file_input], outputs=[output_text, output_word])
374
+
375
+ with gr.Row():
376
+ log_text = gr.Textbox(label="Log Content", interactive=True, lines=1)
377
+
378
+ with gr.Row():
379
+ view_log_button = gr.Button("View Log", elem_classes=["custom-button"])
380
+ download_log_button = gr.Button("Download Log File", elem_classes=["custom-button"])
381
+ clear_log_button = gr.Button("Clear Log File", elem_classes=["custom-button"])
382
+
383
+ view_log_button.click(fn=read_log_file, inputs=[], outputs=log_text)
384
+ download_log_button.click(fn=get_log_file, inputs=[], outputs=[])
385
+ clear_log_button.click(fn=clear_log_file, inputs=[], outputs=[])
386
+
387
+
388
+ demo.launch(share=True)
389
+
390
+
391
+ if __name__ == "__main__":
392
+ main()