arjunanand13 commited on
Commit
6689b55
·
verified ·
1 Parent(s): ca0aea4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -0
app.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import zipfile
4
+ import json
5
+ import pandas as pd
6
+ import datetime
7
+ import shutil
8
+ import hashlib
9
+ from io import StringIO
10
+ from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
11
+ from pdfminer.converter import TextConverter
12
+ from pdfminer.layout import LAParams
13
+ from pdfminer.pdfpage import PDFPage
14
+ from PyPDF2 import PdfReader
15
+ from openai import OpenAI, RateLimitError
16
+ import backoff
17
+ import re
18
+
19
+ class PDFUtils:
20
+ @staticmethod
21
+ def extract_text_with_pdfminer(path):
22
+ rsrcmgr = PDFResourceManager()
23
+ retstr = StringIO()
24
+ codec = 'utf-8'
25
+ laparams = LAParams()
26
+ device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
27
+
28
+ with open(path, 'rb') as fp:
29
+ interpreter = PDFPageInterpreter(rsrcmgr, device)
30
+ for page in PDFPage.get_pages(fp, check_extractable=True):
31
+ interpreter.process_page(page)
32
+
33
+ text = retstr.getvalue()
34
+ return text
35
+
36
+ @staticmethod
37
+ def extract_text_with_pypdf2(path):
38
+ reader = PdfReader(path)
39
+ text = ''.join(page.extract_text() for page in reader.pages)
40
+ return text
41
+
42
+ @staticmethod
43
+ def convert_pdf_to_text(path):
44
+ text = PDFUtils.extract_text_with_pdfminer(path)
45
+ if text is None:
46
+ print("Processing using PyPDF2")
47
+ text = PDFUtils.extract_text_with_pypdf2(path)
48
+ return text
49
+
50
+ class OpenAIClassifier:
51
+ def __init__(self, api_key):
52
+ self.client = OpenAI(api_key=api_key)
53
+ self.processed_resumes = set()
54
+
55
+ @backoff.on_exception(backoff.expo, RateLimitError)
56
+ def completions_with_backoff(self, **kwargs):
57
+ return self.client.chat.completions.create(**kwargs)
58
+
59
+ def hash_resume_text(self, resume_text):
60
+ return hashlib.md5(resume_text.encode()).hexdigest()
61
+
62
+ def classify_resume(self, resume_text, questions_string):
63
+ resume_hash = self.hash_resume_text(resume_text)
64
+ if resume_hash in self.processed_resumes:
65
+ return "Already Processed"
66
+
67
+ response = self.client.chat.completions.create(
68
+ model="gpt-3.5-turbo",
69
+ messages=[
70
+ {"role": "system", "content": f"As a very strict hiring manager who is evaluating a resume. Answer each question, let questions be keys and answers be values {questions_string} As a hiring manager parse through the resume thoroughly and answer the following questions with the same index in dictionary format. In the experience section, if there is no direct reference to the number of years of experience, count the number of years from the least present year in the experience section."},
71
+ {"role": "user", "content": resume_text}
72
+ ],
73
+ temperature=0.7,
74
+ max_tokens=516
75
+ )
76
+
77
+ summary = str(response.choices[0].message)
78
+ self.processed_resumes.add(resume_hash)
79
+
80
+ # Extract JSON substring using regular expression
81
+ json_match = re.search(r"\{.*\}", summary)
82
+ if json_match:
83
+ return json_match.group(0) # Return only the JSON part
84
+ else:
85
+ return "{}"
86
+
87
+ def read_json_file(file_path):
88
+ with open(file_path, 'r') as json_file:
89
+ json_data = json.load(json_file)
90
+ return json.dumps(json_data, indent=2)
91
+
92
+ def process_text(text):
93
+ return text.replace('\\n', '<br>') if text else "Error: Text is None"
94
+
95
+ def process_pdf(file, model_choice, openai_classifier, questions_string):
96
+ data = PDFUtils.convert_pdf_to_text(file)
97
+ if model_choice == "openai":
98
+ classification = openai_classifier.classify_resume(data, questions_string)
99
+ print(f"Debug: classification output:\n{classification}\n") # Debugging line to confirm JSON structure
100
+ return {"file_path": file, "result": process_text(classification)}
101
+ else:
102
+ print("Only openai can be utilized")
103
+
104
+ def unzip_and_process(zip_file, model_choice, openai_classifier, questions_string):
105
+ extract_folder, selected_folder, rejected_folder, error_folder = 'extracted_files/', 'extracted_files/Selected/', 'extracted_files/Rejected/', 'extracted_files/Error/'
106
+ os.makedirs(extract_folder, exist_ok=True)
107
+ os.makedirs(selected_folder, exist_ok=True)
108
+ os.makedirs(rejected_folder, exist_ok=True)
109
+ os.makedirs(error_folder, exist_ok=True)
110
+
111
+ for root, dirs, files in os.walk(extract_folder):
112
+ for file_name in files:
113
+ os.remove(os.path.join(root, file_name))
114
+
115
+ with zipfile.ZipFile(zip_file, 'r') as zip_ref:
116
+ zip_ref.extractall(extract_folder)
117
+
118
+ df_results = pd.DataFrame()
119
+ questions_dict = json.loads(questions_string)
120
+ questions_list = list(questions_dict.values())
121
+ df_results = pd.DataFrame(columns=questions_list)
122
+
123
+ for root, dirs, files in os.walk(extract_folder):
124
+ for file_name in files:
125
+ file_path = os.path.join(root, file_name)
126
+ if file_path.lower().endswith('.pdf'):
127
+ try:
128
+ result = process_pdf(file_path, model_choice, openai_classifier, questions_string)
129
+
130
+ # If already processed, skip this file
131
+ if result['result'] == "Already Processed":
132
+ print(f"{file_name} is already processed. Skipping.")
133
+ continue
134
+
135
+ cleaned_data_str = result['result'].replace("<br>", "").replace("\\", "")
136
+
137
+ # Attempt to parse JSON data
138
+ data_dict = json.loads(cleaned_data_str)
139
+ df_resume = pd.DataFrame(data_dict.items(), columns=["Key", os.path.basename(file_path)])
140
+ df_resume["Key"] = df_resume["Key"].replace(questions_dict)
141
+ df_results = pd.concat([df_results, df_resume.set_index(["Key"]).T.reset_index(drop=True)], axis=0, ignore_index=True)
142
+
143
+ # Decide on the destination based on the final selection key
144
+ selection_rejection = data_dict.get(list(data_dict.keys())[-1])
145
+ destination = selected_folder if selection_rejection == "Selected" else rejected_folder if selection_rejection == "Rejected" else error_folder
146
+ shutil.move(file_path, os.path.join(destination, os.path.basename(file_path)))
147
+
148
+ except json.JSONDecodeError as e:
149
+ print(f"JSON decoding error for {file_path}: {e}")
150
+ shutil.move(file_path, os.path.join(error_folder, file_name))
151
+ except Exception as ex:
152
+ print(f"Error processing file {file_path}: {ex}")
153
+ shutil.move(file_path, os.path.join(error_folder, file_name))
154
+ else:
155
+ shutil.move(file_path, os.path.join(error_folder, file_name))
156
+ print(f"File '{file_name}' is not a PDF. Moved to error directory.")
157
+
158
+ # Save processed results to an Excel file
159
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
160
+ excel_file = f'extracted_files/output_results_{timestamp}.xlsx'
161
+ df_results.to_excel(excel_file, index=False)
162
+ print(f"Processed resumes saved to {excel_file}")
163
+ return excel_file # Return the path to the Excel file
164
+
165
+ def run_interface(questions_json, resumes_zip):
166
+ # Load questions.json content
167
+ questions_string = questions_json.read().decode("utf-8")
168
+
169
+ # Write the ZIP file to disk
170
+ with open("uploaded_resumes.zip", "wb") as f:
171
+ f.write(resumes_zip.read())
172
+
173
+ openai_classifier = OpenAIClassifier(api_key="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")
174
+ output_file = unzip_and_process("uploaded_resumes.zip", "openai", openai_classifier, questions_string)
175
+
176
+ return output_file # Return the Excel file path as Gradio output
177
+
178
+ # Set up the Gradio interface
179
+ interface = gr.Interface(
180
+ fn=run_interface,
181
+ inputs=[
182
+ gr.File(label="Upload questions.json"),
183
+ gr.File(label="Upload ZIP of Resumes")
184
+ ],
185
+ outputs=gr.File(label="Processed Results Excel")
186
+ )
187
+
188
+ interface.launch()