Spaces:
Sleeping
Sleeping
File size: 5,034 Bytes
4470c3e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
import fitz
import faiss
import torch
import requests
import json
import time
import gradio as gr
import datetime
import os
from sentence_transformers import SentenceTransformer
embed_model = SentenceTransformer("intfloat/multilingual-e5-large-instruct")
chunks = []
index = None
qa_history = []
uploaded_filename = ""
def split_into_chunks(text, chunk_size=512, overlap=64):
words = text.split()
return [" ".join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size - overlap)]
def get_embeddings(texts):
prompts = [f"query: {t}" for t in texts]
return embed_model.encode(prompts, normalize_embeddings=True)
def ask_question_stream(query, history):
if index is None:
yield "โ Please upload and process a PDF first."
return
query_vec = get_embeddings([query])[0].reshape(1, -1)
_, I = index.search(query_vec, 4)
context = "\n".join([chunks[i] for i in I[0]])
prompt = f"""Answer the question using only the below context.
Context:
{context}
Question: {query}
Answer:"""
headers = {
"Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
"Content-Type": "application/json"
}
payload = {
"model": "deepseek/deepseek-chat-v3-0324:free",
"messages": [{"role": "user", "content": prompt}]
}
try:
res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, data=json.dumps(payload))
res_json = res.json()
response = res_json["choices"][0]["message"]["content"]
qa_history.append((query, response))
words = response.strip().split()
for i in range(len(words)):
yield " ".join(words[:i+1])
time.sleep(0.02)
except Exception as e:
yield f"โ Error: {str(e)}"
def process_pdf(pdf_file):
global chunks, index, uploaded_filename
if pdf_file is None:
return "โ No file selected."
uploaded_filename = pdf_file.name.split("/")[-1]
doc = fitz.open(pdf_file.name)
full_text = "\n".join([page.get_text() for page in doc])
chunks = split_into_chunks(full_text)
embeddings = get_embeddings(chunks)
if not embeddings.any():
return "โ No text extracted."
dim = embeddings[0].shape[0]
index = faiss.IndexFlatIP(dim)
index.add(embeddings)
return "โ
Processed. Ready for Q&A."
def clear_cache():
global chunks, index, qa_history, uploaded_filename
chunks, index, qa_history, uploaded_filename = [], None, [], ""
return "๐๏ธ Cache cleared."
def export_history():
if not qa_history:
return None
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"qa_history_{timestamp}.txt"
with open(filename, "w", encoding="utf-8") as f:
for q, a in qa_history:
f.write(f"Q: {q}\nA: {a}\n\n")
return filename
custom_css = """
#popup-alert {
background-color: #fef3c7;
color: #92400e;
padding: 12px 20px;
border-radius: 8px;
border: 1px solid #fcd34d;
font-weight: bold;
position: relative;
margin-bottom: 12px;
}
#popup-alert button {
position: absolute;
top: 4px;
right: 8px;
background: none;
color: #92400e;
border: none;
font-size: 18px;
cursor: pointer;
}
"""
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as app:
with gr.Row():
gr.HTML(
"""<div style='text-align:center'>
<h2>๐ค Chat with Your Research Paper</h2>
<div id='popup-alert' style="display: inline-block;">
โ ๏ธ Please click โClear Cacheโ before uploading a new PDF.
<button onclick="this.parentElement.style.display='none';">×</button>
</div>
</div>"""
)
with gr.Row(equal_height=False):
with gr.Column(scale=1, min_width=250):
pdf_upload = gr.File(label="๐ Upload PDF", file_types=[".pdf"])
upload_status = gr.Textbox(label="Status", interactive=False)
clear_button = gr.Button("๐งน Clear Cache")
export_button = gr.Button("๐ค Export Q&A History")
download_box = gr.File(visible=False)
pdf_upload.change(fn=process_pdf, inputs=pdf_upload, outputs=upload_status)
clear_button.click(fn=clear_cache, outputs=upload_status)
export_button.click(fn=export_history, inputs=[], outputs=download_box)
download_box.change(lambda x: gr.update(visible=True) if x else gr.update(visible=False), inputs=download_box, outputs=download_box)
with gr.Column(scale=4, min_width=600):
gr.ChatInterface(
fn=ask_question_stream,
chatbot=gr.Chatbot(label="๐ PDF Chatbot", show_copy_button=True),
textbox=gr.Textbox(placeholder="Ask about the uploaded paper...", container=False, scale=7),
examples=["What is the conclusion?", "Who are the authors?", "What are the key findings?"]
)
app.launch()
|