Spaces:
Sleeping

superbsaeed commited on
Commit
95f0130
Β·
verified Β·
1 Parent(s): 0ce6824

Create APP.PY

Browse files
Files changed (1) hide show
  1. APP.PY +114 -0
APP.PY ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from pypdf import PdfReader
4
+ from groq import Groq
5
+
6
+ def extract_text_from_pdf(pdf_path):
7
+ reader = PdfReader(pdf_path)
8
+ pages = []
9
+ for i, page in enumerate(reader.pages):
10
+ text = page.extract_text()
11
+ if text and text.strip():
12
+ pages.append(f"[Page {i+1}]\n{text.strip()}")
13
+ return "\n\n".join(pages) if pages else None
14
+
15
+ def truncate_text(text, max_chars=6000):
16
+ if len(text) <= max_chars:
17
+ return text
18
+ return text[:4000] + "\n\n...[middle truncated]...\n\n" + text[-2000:]
19
+
20
+ def ask_groq(pdf_text, question, model, history):
21
+ client = Groq(api_key=os.environ["GROQ_API_KEY"])
22
+ safe_pdf_text = truncate_text(pdf_text)
23
+
24
+ messages = [{
25
+ "role": "system",
26
+ "content": (
27
+ "You are a helpful assistant. Answer questions ONLY from the provided PDF. "
28
+ "If the answer is not in the document, say so. Mention page numbers when possible."
29
+ )
30
+ }]
31
+
32
+ for user_msg, bot_msg in history:
33
+ messages.append({"role": "user", "content": user_msg})
34
+ messages.append({"role": "assistant", "content": bot_msg})
35
+
36
+ if not history:
37
+ content = f"PDF Content:\n\n{safe_pdf_text}\n\n---\nQuestion: {question}"
38
+ else:
39
+ content = question
40
+
41
+ messages.append({"role": "user", "content": content})
42
+
43
+ response = client.chat.completions.create(
44
+ model=model,
45
+ messages=messages,
46
+ temperature=0.2,
47
+ max_tokens=1024,
48
+ )
49
+ return response.choices[0].message.content
50
+
51
+ def load_pdf(pdf_file, state):
52
+ if pdf_file is None:
53
+ return state, "⚠️ Please upload a PDF.", gr.update(interactive=False)
54
+ pdf_text = extract_text_from_pdf(pdf_file)
55
+ if not pdf_text:
56
+ return state, "❌ Could not extract text. Try a non-scanned PDF.", gr.update(interactive=False)
57
+ state["pdf_text"] = pdf_text
58
+ state["history"] = []
59
+ pages = pdf_text.count("[Page ")
60
+ words = len(pdf_text.split())
61
+ return state, f"βœ… Loaded! {pages} page(s), ~{words:,} words.\nNow ask your questions!", gr.update(interactive=True)
62
+
63
+ def ask_question(question, model, state, chat_history):
64
+ if not question.strip():
65
+ return chat_history, state, ""
66
+ if not state.get("pdf_text"):
67
+ chat_history.append((question, "⚠️ Please load a PDF first."))
68
+ return chat_history, state, ""
69
+ try:
70
+ answer = ask_groq(state["pdf_text"], question, model, state["history"])
71
+ state["history"].append((question, answer))
72
+ chat_history.append((question, answer))
73
+ except Exception as e:
74
+ chat_history.append((question, f"❌ Error: {e}"))
75
+ return chat_history, state, ""
76
+
77
+ def clear_chat(state):
78
+ state["history"] = []
79
+ return [], state
80
+
81
+ MODELS = [
82
+ "llama-3.3-70b-versatile",
83
+ "llama-3.1-8b-instant",
84
+ "llama3-70b-8192",
85
+ "gemma2-9b-it",
86
+ ]
87
+
88
+ with gr.Blocks(title="PDF Q&A β€” Groq", theme=gr.themes.Soft()) as demo:
89
+
90
+ state = gr.State({"pdf_text": "", "history": []})
91
+
92
+ gr.Markdown("# πŸ“„ PDF Q&A App\n### Upload a PDF β†’ Ask questions β†’ Get AI answers")
93
+
94
+ with gr.Row():
95
+ with gr.Column(scale=1):
96
+ pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"], type="filepath")
97
+ upload_btn = gr.Button("πŸ“€ Load PDF", variant="primary", size="lg")
98
+ status = gr.Textbox(label="Status", value="Upload a PDF to begin...", lines=3, interactive=False)
99
+ model_drop = gr.Dropdown(choices=MODELS, value=MODELS[0], label="πŸ€– Groq Model")
100
+
101
+ with gr.Column(scale=2):
102
+ chatbot = gr.Chatbot(label="Conversation", height=420)
103
+ with gr.Row():
104
+ q_input = gr.Textbox(label="Your Question", placeholder="e.g. Summarize this document", lines=2, interactive=False, scale=4)
105
+ with gr.Column(scale=1):
106
+ ask_btn = gr.Button("πŸ” Ask", variant="primary")
107
+ clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
108
+
109
+ upload_btn.click(load_pdf, [pdf_input, state], [state, status, q_input])
110
+ ask_btn.click(ask_question, [q_input, model_drop, state, chatbot], [chatbot, state, q_input])
111
+ q_input.submit(ask_question, [q_input, model_drop, state, chatbot], [chatbot, state, q_input])
112
+ clear_btn.click(clear_chat, [state], [chatbot, state])
113
+
114
+ demo.launch() # ← No share=True needed on Hugging Face