rahulmolasi's picture
Update app.py
b3b0bf3 verified
Raw History Blame Contribute Delete
3.7 kB
import os
from groq import Groq
import gradio as gr
import pandas as pd
from PyPDF2 import PdfReader
from docx import Document
# -------------------------------
# Get your API key from environment
# -------------------------------
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("Please set your GROQ_API_KEY environment variable!")
# Initialize Groq client
client = Groq(api_key=GROQ_API_KEY)
# -------------------------------
# Helper function: extract text from uploaded files
# -------------------------------
def extract_file_text(uploaded_file):
if not uploaded_file:
return ""
filename = uploaded_file.name.lower()
try:
if filename.endswith(".txt"):
with open(uploaded_file.name, "r", encoding="utf-8") as f:
return f.read()
elif filename.endswith(".pdf"):
reader = PdfReader(uploaded_file.name)
return "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
elif filename.endswith(".docx"):
doc = Document(uploaded_file.name)
return "\n".join([p.text for p in doc.paragraphs])
elif filename.endswith(".csv"):
df = pd.read_csv(uploaded_file.name)
return df.to_string()
elif filename.endswith(".xlsx"):
df = pd.read_excel(uploaded_file.name)
return df.to_string()
else:
return "[Unsupported file type]"
except Exception as e:
return f"[Error reading file: {str(e)}]"
# -------------------------------
# Chatbot logic
# -------------------------------
def healthcare_assistant(message, history, uploaded_file):
# Extract file text
file_text = extract_file_text(uploaded_file)
# System prompt
messages = [
{
"role": "system",
"content": "You are a helpful Professional Role Pathway Bot — turns a Job Description or uploaded file content into a personalized, step-by-step upskilling plan."
}
]
# Add previous chat history
for user_msg, bot_msg in history:
messages.append({"role": "user", "content": user_msg})
if bot_msg:
messages.append({"role": "assistant", "content": bot_msg})
# Combine user message + file content
combined_message = message
if file_text:
combined_message += "\n\nFile content:\n" + file_text
messages.append({"role": "user", "content": combined_message})
# Call Groq API
response = client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=messages
)
return response.choices[0].message.content
# -------------------------------
# Gradio UI
# -------------------------------
with gr.Blocks() as demo:
history = gr.State([]) # store chat history
gr.Markdown("## Professional Role Pathway Bot 🤖\nPaste JD, answer prompts, or upload a file to get personalized learning roadmap.")
chatbox = gr.Chatbot()
with gr.Row():
txt = gr.Textbox(label="Type your message", placeholder="Enter text here...")
file_input = gr.File(label="Upload file (optional)", file_types=[".txt", ".pdf", ".docx", ".csv", ".xlsx"])
submit_btn = gr.Button("Send")
# Respond function
def respond(message, history, uploaded_file):
response = healthcare_assistant(message, history, uploaded_file)
history.append((message, response))
return history, ""
submit_btn.click(respond, inputs=[txt, history, file_input], outputs=[chatbox, txt])
# -------------------------------
# Launch
# -------------------------------
if __name__ == "__main__":
demo.launch()