Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,22 +6,31 @@ from huggingface_hub import login
|
|
| 6 |
import pytesseract
|
| 7 |
import torch
|
| 8 |
import os
|
| 9 |
-
import spaces
|
| 10 |
import re
|
|
|
|
| 11 |
|
|
|
|
| 12 |
login(token=os.environ.get("token"))
|
| 13 |
|
|
|
|
| 14 |
if not torch.cuda.is_available():
|
| 15 |
-
raise RuntimeError("β GPU not detected!")
|
| 16 |
print(f"β
Using GPU: {torch.cuda.get_device_name(0)}")
|
| 17 |
|
|
|
|
| 18 |
model_id = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 19 |
|
| 20 |
def extract_text_from_pdf(file):
|
| 21 |
text = ""
|
| 22 |
with pdfplumber.open(file) as pdf:
|
| 23 |
for page in pdf.pages:
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
return text
|
| 26 |
|
| 27 |
def extract_text_from_docx(file):
|
|
@@ -29,111 +38,106 @@ def extract_text_from_docx(file):
|
|
| 29 |
return "\n".join([para.text for para in doc.paragraphs if para.text.strip() != ""])
|
| 30 |
|
| 31 |
def chunk_text(text, max_chars=6000):
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
else:
|
| 37 |
-
chunks.append(
|
| 38 |
-
|
| 39 |
-
if
|
| 40 |
-
chunks.append(
|
| 41 |
return chunks
|
| 42 |
|
| 43 |
-
def create_prompt(
|
| 44 |
return f"""
|
| 45 |
-
Analyze the following resume and extract
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
Name: ...
|
| 57 |
-
Email: ...
|
| 58 |
-
Phone: ...
|
| 59 |
-
Skills:
|
| 60 |
-
- ...
|
| 61 |
-
- ...
|
| 62 |
-
Education: ...
|
| 63 |
-
Experience:
|
| 64 |
-
- ...
|
| 65 |
-
- ...
|
| 66 |
|
| 67 |
CONTENT:
|
| 68 |
-
{
|
| 69 |
"""
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
|
| 73 |
-
if
|
| 74 |
-
return
|
| 75 |
-
return
|
| 76 |
|
| 77 |
@spaces.GPU(duration=60)
|
| 78 |
-
def
|
| 79 |
ext = os.path.splitext(file.name)[-1].lower()
|
|
|
|
| 80 |
if ext == ".pdf":
|
| 81 |
raw_text = extract_text_from_pdf(file)
|
| 82 |
elif ext == ".docx":
|
| 83 |
raw_text = extract_text_from_docx(file)
|
| 84 |
else:
|
| 85 |
-
return "β Unsupported file format
|
| 86 |
|
| 87 |
-
if
|
| 88 |
-
return "β No text found in the document", "β Empty
|
| 89 |
|
| 90 |
chunks = chunk_text(raw_text)
|
|
|
|
| 91 |
|
| 92 |
tokenizer = AutoTokenizer.from_pretrained(model_id, token=os.environ.get("token"))
|
| 93 |
model = AutoModelForCausalLM.from_pretrained(
|
| 94 |
-
model_id,
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
| 96 |
)
|
| 97 |
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 98 |
|
| 99 |
-
final_summary = ""
|
| 100 |
for i, chunk in enumerate(chunks):
|
| 101 |
if cancel_flag:
|
| 102 |
-
return "β Analysis cancelled by user.", "β
|
|
|
|
| 103 |
prompt = create_prompt(chunk)
|
| 104 |
result = generator(prompt, max_new_tokens=1024, do_sample=False)[0]["generated_text"]
|
| 105 |
-
|
| 106 |
-
|
| 107 |
|
| 108 |
-
return
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
gr.Markdown("## π Resume Analyzer β Extract key information (Name, Email, Skills, etc)")
|
| 113 |
|
| 114 |
with gr.Row():
|
| 115 |
with gr.Column(scale=1):
|
| 116 |
-
file_input = gr.File(label="π Upload Resume (PDF
|
| 117 |
with gr.Row():
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
status_box = gr.Textbox(label="π Status", value="β³ Waiting...", interactive=False)
|
| 121 |
|
| 122 |
with gr.Column(scale=2):
|
| 123 |
-
|
| 124 |
|
| 125 |
cancel_flag = gr.State(False)
|
| 126 |
|
| 127 |
-
|
| 128 |
-
fn=
|
| 129 |
inputs=[file_input, cancel_flag],
|
| 130 |
-
outputs=[
|
| 131 |
)
|
| 132 |
|
| 133 |
-
|
| 134 |
fn=lambda: gr.update(value=True),
|
| 135 |
inputs=[],
|
| 136 |
outputs=[cancel_flag]
|
| 137 |
)
|
| 138 |
|
| 139 |
-
demo.launch(server_name="0.0.0.0", server_port=7860
|
|
|
|
| 6 |
import pytesseract
|
| 7 |
import torch
|
| 8 |
import os
|
|
|
|
| 9 |
import re
|
| 10 |
+
import spaces
|
| 11 |
|
| 12 |
+
# π Authenticate Hugging Face token
|
| 13 |
login(token=os.environ.get("token"))
|
| 14 |
|
| 15 |
+
# β
Ensure GPU is available
|
| 16 |
if not torch.cuda.is_available():
|
| 17 |
+
raise RuntimeError("β GPU not detected! Please enable GPU in Space settings.")
|
| 18 |
print(f"β
Using GPU: {torch.cuda.get_device_name(0)}")
|
| 19 |
|
| 20 |
+
# π§ Model
|
| 21 |
model_id = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 22 |
|
| 23 |
def extract_text_from_pdf(file):
|
| 24 |
text = ""
|
| 25 |
with pdfplumber.open(file) as pdf:
|
| 26 |
for page in pdf.pages:
|
| 27 |
+
page_text = page.extract_text()
|
| 28 |
+
if page_text:
|
| 29 |
+
text += page_text + "\n"
|
| 30 |
+
else:
|
| 31 |
+
img = page.to_image(resolution=300).original
|
| 32 |
+
ocr_text = pytesseract.image_to_string(img)
|
| 33 |
+
text += ocr_text + "\n"
|
| 34 |
return text
|
| 35 |
|
| 36 |
def extract_text_from_docx(file):
|
|
|
|
| 38 |
return "\n".join([para.text for para in doc.paragraphs if para.text.strip() != ""])
|
| 39 |
|
| 40 |
def chunk_text(text, max_chars=6000):
|
| 41 |
+
paragraphs = text.split("\n")
|
| 42 |
+
chunks, current_chunk = [], ""
|
| 43 |
+
for para in paragraphs:
|
| 44 |
+
if len(current_chunk) + len(para) < max_chars:
|
| 45 |
+
current_chunk += para + "\n"
|
| 46 |
else:
|
| 47 |
+
chunks.append(current_chunk)
|
| 48 |
+
current_chunk = para + "\n"
|
| 49 |
+
if current_chunk:
|
| 50 |
+
chunks.append(current_chunk)
|
| 51 |
return chunks
|
| 52 |
|
| 53 |
+
def create_prompt(text_chunk):
|
| 54 |
return f"""
|
| 55 |
+
Analyze the following resume and extract ONLY the following fields in clean text format with clear labels:
|
| 56 |
+
|
| 57 |
+
Name
|
| 58 |
+
Email
|
| 59 |
+
Phone
|
| 60 |
+
Skills (bullet points)
|
| 61 |
+
Education (bullet points)
|
| 62 |
+
Experience (bullet points with org, role, period)
|
| 63 |
+
Projects (bullet points with brief descriptions)
|
| 64 |
+
|
| 65 |
+
Return only these details and nothing else.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
CONTENT:
|
| 68 |
+
{text_chunk}
|
| 69 |
"""
|
| 70 |
|
| 71 |
+
def extract_final_response(raw_output):
|
| 72 |
+
matches = list(re.finditer(r"\\bName\\s*:", raw_output))
|
| 73 |
+
if len(matches) >= 2:
|
| 74 |
+
return raw_output[matches[1].start():].strip()
|
| 75 |
+
return raw_output.strip()
|
| 76 |
|
| 77 |
@spaces.GPU(duration=60)
|
| 78 |
+
def analyze_document(file, cancel_flag):
|
| 79 |
ext = os.path.splitext(file.name)[-1].lower()
|
| 80 |
+
|
| 81 |
if ext == ".pdf":
|
| 82 |
raw_text = extract_text_from_pdf(file)
|
| 83 |
elif ext == ".docx":
|
| 84 |
raw_text = extract_text_from_docx(file)
|
| 85 |
else:
|
| 86 |
+
return "β Unsupported file format. Please upload a PDF or DOCX.", "β Invalid format"
|
| 87 |
|
| 88 |
+
if len(raw_text.strip()) == 0:
|
| 89 |
+
return "β No text found in the document.", "β Empty document"
|
| 90 |
|
| 91 |
chunks = chunk_text(raw_text)
|
| 92 |
+
full_summary = ""
|
| 93 |
|
| 94 |
tokenizer = AutoTokenizer.from_pretrained(model_id, token=os.environ.get("token"))
|
| 95 |
model = AutoModelForCausalLM.from_pretrained(
|
| 96 |
+
model_id,
|
| 97 |
+
device_map="auto",
|
| 98 |
+
torch_dtype=torch.float16,
|
| 99 |
+
token=os.environ.get("token"),
|
| 100 |
+
trust_remote_code=True
|
| 101 |
)
|
| 102 |
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 103 |
|
|
|
|
| 104 |
for i, chunk in enumerate(chunks):
|
| 105 |
if cancel_flag:
|
| 106 |
+
return "β Analysis cancelled by user.", "β Terminated by user"
|
| 107 |
+
|
| 108 |
prompt = create_prompt(chunk)
|
| 109 |
result = generator(prompt, max_new_tokens=1024, do_sample=False)[0]["generated_text"]
|
| 110 |
+
cleaned = extract_final_response(result)
|
| 111 |
+
full_summary += cleaned + "\n\n---\n\n"
|
| 112 |
|
| 113 |
+
return full_summary.strip(), "β
Completed"
|
| 114 |
|
| 115 |
+
with gr.Blocks(title="Smart Resume Parser - AI Powered") as demo:
|
| 116 |
+
gr.Markdown("## π Resume Parser β Extract Key Info using Mistral-7B")
|
|
|
|
| 117 |
|
| 118 |
with gr.Row():
|
| 119 |
with gr.Column(scale=1):
|
| 120 |
+
file_input = gr.File(label="π Upload Resume (PDF/DOCX)")
|
| 121 |
with gr.Row():
|
| 122 |
+
analyze_button = gr.Button("π Analyze", variant="primary")
|
| 123 |
+
terminate_button = gr.Button("β Terminate", variant="stop")
|
| 124 |
+
status_box = gr.Textbox(label="π Status", value="β³ Waiting for input...", interactive=False)
|
| 125 |
|
| 126 |
with gr.Column(scale=2):
|
| 127 |
+
output_box = gr.Textbox(label="π§ Extracted Resume Info", lines=30, interactive=False)
|
| 128 |
|
| 129 |
cancel_flag = gr.State(False)
|
| 130 |
|
| 131 |
+
analyze_button.click(
|
| 132 |
+
fn=analyze_document,
|
| 133 |
inputs=[file_input, cancel_flag],
|
| 134 |
+
outputs=[output_box, status_box]
|
| 135 |
)
|
| 136 |
|
| 137 |
+
terminate_button.click(
|
| 138 |
fn=lambda: gr.update(value=True),
|
| 139 |
inputs=[],
|
| 140 |
outputs=[cancel_flag]
|
| 141 |
)
|
| 142 |
|
| 143 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|