PDF_Reader / app.py
BraWler666's picture
Update app.py
79c01c2 verified
Raw History Blame Contribute Delete
2.95 kB
import gradio as gr
import requests
import os
from PyPDF2 import PdfReader
# Add your DeepSeek API Key
DEEPSEEK_API_KEY = os.environ.get("DEEPSEEK_API_KEY", "your-key-here")
def extract_pdf_text(pdf_file):
reader = PdfReader(pdf_file)
text = ""
for page in reader.pages:
text += page.extract_text() or ""
return text.strip()
def ask_pdf(pdf_file, question):
if not pdf_file or not question:
return "⚠️ Please upload a PDF and enter a question."
content = extract_pdf_text(pdf_file)
prompt = f"Answer this question based on the following PDF content:\n\n{content[:4000]}\n\nQuestion: {question}"
headers = {
"Authorization": f"Bearer {DEEPSEEK_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
}
try:
response = requests.post("https://api.deepseek.com/chat/completions", json=data, headers=headers)
result = response.json()
return result['choices'][0]['message']['content']
except Exception as e:
return f"❌ Error: {e}"
with gr.Blocks(css="""
body {
background-color: #111;
color: #f5f5f5;
font-family: 'Inter', sans-serif;
}
.gr-button {
background: #6a0dad;
color: white;
font-weight: bold;
border-radius: 8px;
border: 2px solid #6a0dad;
transition: 0.3s;
}
.gr-button:hover {
background: #8e44ad;
border-color: #8e44ad;
}
.gr-box, .gr-textbox, .gr-file {
background-color: #1c1c1c;
border: 1px solid #333;
border-radius: 10px;
color: white;
}
footer {
visibility: hidden;
}
.title {
font-size: 2.4rem;
text-align: center;
font-weight: 700;
margin-top: 1.5rem;
background: linear-gradient(to right, #ff4ecb, #8873f5);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.subtitle {
font-size: 1.2rem;
text-align: center;
color: #aaa;
margin-bottom: 2rem;
}
""") as demo:
gr.Markdown("""
<div class="title">✨ PDF Genius Chatbot</div>
<div class="subtitle">Ask your PDFs anything β€” powered by DeepSeek AI</div>
""")
with gr.Row():
with gr.Column():
pdf_input = gr.File(label="πŸ“„ Upload your PDF", file_types=[".pdf"])
question_input = gr.Textbox(label="❓ Ask a question about your PDF", placeholder="e.g. Summarize this document...", lines=2)
btn = gr.Button("πŸš€ Ask the PDF")
with gr.Column():
output = gr.Textbox(label="πŸ’‘ Answer", lines=14)
btn.click(fn=ask_pdf, inputs=[pdf_input, question_input], outputs=output)
demo.launch()