import gradio as gr
import requests
import os
import PyPDF2
from io import BytesIO
# Hugging Face API and model
HF_API_TOKEN = os.getenv("HF_API_TOKEN")
HF_API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
MODEL_CHECK_PROMPT = "Say hello!"
# ✅ Check whether the API key and model are working correctly
def check_api_ready():
if not HF_API_TOKEN:
return False, "❌ HF_API_TOKEN not set. Please add in Space secrets."
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
try:
resp = requests.post(HF_API_URL, headers=headers, json={"inputs": MODEL_CHECK_PROMPT}, timeout=20)
if resp.status_code == 200:
data = resp.json()
if isinstance(data, dict) and "error" in data:
return False, f"❌ Model Error: {data['error']}"
if isinstance(data, list) and data[0].get("generated_text"):
return True, "✅ Model is ready!"
elif resp.status_code == 401:
return False, "❌ Unauthorized. Check your API token."
else:
return False, f"❌ Unexpected API response: {resp.text}"
except Exception as e:
return False, f"❌ API connection failed: {str(e)}"
# ✅ Tooltip animation HTML from Lottie JSON (place Robotics-Students.json in Space root)
def lottie_html():
return """
"""
# ✅ PDF text extractor
def extract_text_from_pdf(pdf_file):
reader = PyPDF2.PdfReader(BytesIO(pdf_file.read()))
return "\n".join([page.extract_text() or "" for page in reader.pages]).strip()
# ✅ Generate questions and answers using language model
def ai_generate_questions(resume_text, job_title):
prompt = (
f"You are an AI interview coach.\n"
f"Candidate Resume:\n{resume_text}\n"
f"Target Role: {job_title}\n"
f"Generate 10 realistic interview questions based on this person’s resume, "
f"and for each question provide a coaching tip to help them answer effectively."
)
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
payload = {"inputs": prompt, "parameters": {"max_new_tokens": 512, "temperature": 0.7}}
try:
response = requests.post(HF_API_URL, headers=headers, json=payload, timeout=60)
data = response.json()
if "error" in data:
return f"
❌ API Error: {data['error']}
"
return data[0]["generated_text"].strip()
except Exception as e:
return f"❌ Exception: {str(e)}
"
# ✅ Format final output HTML
def render_output(name, job, status, queue, messages, model_message, show_lottie=True):
lottie_side = lottie_html() if show_lottie else ""
model_msg = f"{model_message}
" if model_message else ""
left_panel = f"""
{lottie_side}
🤖 ROBOT RESUME ANALYZER
Status: {status}
Current: {name}
Position: {job}
Analysis Progress:
👥
QUEUE
{queue}
Analyzing Next...
{model_msg}
"""
return f"""
"""
# ✅ Main app logic with staged UI updates
def interface(pdf_file, job_title):
is_ready, msg = check_api_ready()
if not is_ready:
err_html = f"ERROR: {msg}
"
return render_output("---", "---", "Unavailable", 0, err_html, msg, show_lottie=False)
if not pdf_file:
return render_output("---", "---", "Waiting for PDF", 1, "Please upload a PDF resume.", msg)
if not job_title.strip():
name = pdf_file.name.replace('.pdf','')
return render_output(name, "---", "Waiting for Job Title", 1, "Please enter a target job title.", msg)
name = pdf_file.name.replace(".pdf", "")
try:
pdf_file.seek(0)
resume_text = extract_text_from_pdf(pdf_file)
if not resume_text:
raise Exception("PDF contains no readable text")
except Exception as e:
return render_output(name, job_title, "PDF Error", 1, f"Failed to extract PDF: {e}
", msg)
yield render_output(name, job_title, "Analyzing...", 1, "Generating questions with AI...", msg)
ai_output = ai_generate_questions(resume_text, job_title)
questions = [q.strip() for q in ai_output.split("\n") if q.strip()]
html = "✅ Interview Questions & Coaching Tips
"
for i, q in enumerate(questions[:10], 1):
html += f""
html += f"Q{i}: {q}
"
yield render_output(name, job_title, "Done ✅", 0, html, msg)
# ✅ Launch Gradio app
with gr.Interface(
fn=interface,
inputs=[
gr.File(label="Upload PDF Resume", type="binary", file_types=[".pdf"]),
gr.Textbox(label="Target Job Title", placeholder="e.g. Data Analyst"),
],
outputs=gr.HTML(),
allow_flagging="never",
title="🤖 AI Resume Analyzer + Interview Coach (PDF + Lottie)",
live=False,
) as demo:
demo.launch()