Spaces:
Sleeping
Sleeping
Update app.py
Browse filesui in tocken and file name in row
app.py
CHANGED
|
@@ -1,194 +1,158 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import uuid
|
| 3 |
-
import sqlite3
|
| 4 |
-
import json
|
| 5 |
-
import re
|
| 6 |
-
import PyPDF2
|
| 7 |
-
import numpy as np
|
| 8 |
-
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
| 9 |
-
from sklearn.metrics.pairwise import cosine_similarity
|
| 10 |
-
|
| 11 |
-
# Local imports
|
| 12 |
-
from database1 import create_db
|
| 13 |
-
from first1 import pdf_query
|
| 14 |
-
|
| 15 |
-
from ans_generator1 import AnswerGenerator
|
| 16 |
-
|
| 17 |
-
import sqlite3, json
|
| 18 |
-
from q_generator1 import QGenerator
|
| 19 |
-
from transformers import pipeline
|
| 20 |
-
# Initialize models
|
| 21 |
-
qgen = QGenerator()
|
| 22 |
-
ansgen = AnswerGenerator()
|
| 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 |
-
return f"
|
| 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 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
# ✅ Gradio UI
|
| 162 |
-
with gr.Blocks(theme="default") as demo:
|
| 163 |
-
gr.Markdown(
|
| 164 |
-
"""
|
| 165 |
-
<div style='text-align: center; padding: 1rem;'>
|
| 166 |
-
<h1 style='color: #3b82f6;'>📄 AI-Powered PDF Q&A System</h1>
|
| 167 |
-
<p style='font-size: 1.1rem;'>Upload your PDFs, generate smart questions, and get intelligent answers.</p>
|
| 168 |
-
</div>
|
| 169 |
-
"""
|
| 170 |
-
)
|
| 171 |
-
|
| 172 |
-
with gr.Tab("📤 1. Upload PDF"):
|
| 173 |
-
gr.Markdown("### 🗂 Upload a PDF File")
|
| 174 |
-
file = gr.File(label="Upload one or more PDFs", file_types=[".pdf"], file_count="multiple")
|
| 175 |
-
|
| 176 |
-
upload_out = gr.Textbox(label="Upload Result", interactive=False)
|
| 177 |
-
file.change(fn=upload_pdf, inputs=file, outputs=upload_out)
|
| 178 |
-
|
| 179 |
-
with gr.Tab("🧠 2. Generate Questions & Answers"):
|
| 180 |
-
gr.Markdown("### 🤖 Generate Questions and Answers from Uploaded PDF")
|
| 181 |
-
token_input = gr.Textbox(label="🔑 Enter Received Token", placeholder="e.g., 123e4567-e89b-12d3-a456...")
|
| 182 |
-
output_box = gr.Textbox(label="📝 Generated Q&A", lines=15, interactive=False)
|
| 183 |
-
gr.Button("🚀 Generate Q&A").click(fn=generate_qa, inputs=token_input, outputs=output_box)
|
| 184 |
-
|
| 185 |
-
with gr.Tab("❓ 3. Ask a Question"):
|
| 186 |
-
gr.Markdown("### 💬 Ask a question based on uploaded PDF")
|
| 187 |
-
token_box = gr.Textbox(label="Token ID", placeholder="e.g., 123e4567-e89b-12d3-a456...")
|
| 188 |
-
question_box = gr.Textbox(label="Type your question", placeholder="What is the main topic discussed?")
|
| 189 |
-
answer_result = gr.Textbox(label="Answer Output", lines=6, interactive=False)
|
| 190 |
-
gr.Button("🎯 Get Answer").click(fn=ask_question, inputs=[token_box, question_box], outputs=answer_result)
|
| 191 |
-
|
| 192 |
-
if __name__ == "__main__":
|
| 193 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 194 |
-
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import uuid
|
| 3 |
+
import sqlite3
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import PyPDF2
|
| 7 |
+
import numpy as np
|
| 8 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
| 9 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 10 |
+
|
| 11 |
+
# Local imports
|
| 12 |
+
from database1 import create_db
|
| 13 |
+
from first1 import pdf_query
|
| 14 |
+
|
| 15 |
+
from ans_generator1 import AnswerGenerator
|
| 16 |
+
|
| 17 |
+
import sqlite3, json
|
| 18 |
+
from q_generator1 import QGenerator
|
| 19 |
+
from transformers import pipeline
|
| 20 |
+
# Initialize models
|
| 21 |
+
qgen = QGenerator()
|
| 22 |
+
ansgen = AnswerGenerator()
|
| 23 |
+
tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base", use_fast=False)
|
| 24 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base")
|
| 25 |
+
qa_model = pipeline("text2text-generation", model=model, tokenizer=tokenizer)
|
| 26 |
+
|
| 27 |
+
# ✅ Upload and process PDF
|
| 28 |
+
def upload_pdf(files):
|
| 29 |
+
try:
|
| 30 |
+
messages = []
|
| 31 |
+
|
| 32 |
+
for file in files:
|
| 33 |
+
filename = file.name
|
| 34 |
+
token = str(uuid.uuid4())
|
| 35 |
+
|
| 36 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
| 37 |
+
text = "".join([page.extract_text() or "" for page in pdf_reader.pages])
|
| 38 |
+
chunks = [text[i:i + 500] for i in range(0, len(text), 500)]
|
| 39 |
+
|
| 40 |
+
create_db(token, chunks, filename, text)
|
| 41 |
+
messages.append(f"✅ Uploaded and stored: {filename}\n🔑 Token: {token}")
|
| 42 |
+
|
| 43 |
+
return "\n\n".join(messages)
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
return f"❌ Error: {str(e)}"
|
| 47 |
+
|
| 48 |
+
# ✅ Generate Questions & Answers
|
| 49 |
+
def generate_qa(token):
|
| 50 |
+
try:
|
| 51 |
+
if not token:
|
| 52 |
+
return "⚠️ Please provide a token."
|
| 53 |
+
|
| 54 |
+
print("📥 Received Token:", token)
|
| 55 |
+
|
| 56 |
+
with sqlite3.connect("my_database.db") as conn:
|
| 57 |
+
cursor = conn.cursor()
|
| 58 |
+
cursor.execute("SELECT chunk_data FROM token_data WHERE token_id = ?", (token,))
|
| 59 |
+
row = cursor.fetchone()
|
| 60 |
+
|
| 61 |
+
if not row:
|
| 62 |
+
return "❌ No data found for this token."
|
| 63 |
+
|
| 64 |
+
chunks = json.loads(row[0])
|
| 65 |
+
qa_pairs = []
|
| 66 |
+
|
| 67 |
+
for i, chunk in enumerate(chunks):
|
| 68 |
+
print(f"\n🔹 Processing chunk {i+1}/{len(chunks)}")
|
| 69 |
+
questions = qgen.generate(chunk)
|
| 70 |
+
print(f"🧠 Questions generated: {questions}")
|
| 71 |
+
|
| 72 |
+
if not questions:
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
for question in questions[:2]:
|
| 76 |
+
prompt = f"Context: {chunk}\n\nQuestion: {question}\n\nAnswer:"
|
| 77 |
+
try:
|
| 78 |
+
result = qa_model(prompt, max_length=256, do_sample=False)
|
| 79 |
+
if isinstance(result, list) and "generated_text" in result[0]:
|
| 80 |
+
answer = result[0]["generated_text"].strip()
|
| 81 |
+
else:
|
| 82 |
+
answer = "N/A"
|
| 83 |
+
|
| 84 |
+
qa_pairs.append(f"Q: {question}\nA: {answer}")
|
| 85 |
+
|
| 86 |
+
except Exception as e:
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
return "\n\n".join(qa_pairs) if qa_pairs else "⚠️ No Q&A pairs generated."
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
return f"❌ Error: {str(e)}"
|
| 93 |
+
|
| 94 |
+
# ✅ Ask a question using token
|
| 95 |
+
def ask_question(token, question):
|
| 96 |
+
try:
|
| 97 |
+
with sqlite3.connect("my_database.db") as conn:
|
| 98 |
+
cursor = conn.cursor()
|
| 99 |
+
cursor.execute("SELECT chunk_data FROM token_data WHERE token_id = ?", (token,))
|
| 100 |
+
row = cursor.fetchone()
|
| 101 |
+
|
| 102 |
+
if not row:
|
| 103 |
+
return "❌ Token not found."
|
| 104 |
+
|
| 105 |
+
chunks = json.loads(row[0])
|
| 106 |
+
processor = pdf_query()
|
| 107 |
+
model = processor.model
|
| 108 |
+
|
| 109 |
+
clean_chunks = [re.sub(r'\s+', ' ', c.strip()) for c in chunks if c.strip()]
|
| 110 |
+
if not clean_chunks:
|
| 111 |
+
return "⚠️ No valid content found in PDF."
|
| 112 |
+
|
| 113 |
+
chunk_embeddings = model.encode(clean_chunks)
|
| 114 |
+
q_embedding = model.encode([question])
|
| 115 |
+
scores = cosine_similarity(q_embedding, chunk_embeddings)[0]
|
| 116 |
+
|
| 117 |
+
top_index = int(np.argmax(scores))
|
| 118 |
+
top_score = float(scores[top_index])
|
| 119 |
+
best_text = clean_chunks[top_index]
|
| 120 |
+
|
| 121 |
+
return f"Q: {question}\nA: {best_text}\nScore: {round(top_score, 3)}"
|
| 122 |
+
|
| 123 |
+
except Exception as e:
|
| 124 |
+
return f"❌ Error: {str(e)}"
|
| 125 |
+
|
| 126 |
+
# ✅ Gradio UI
|
| 127 |
+
with gr.Blocks(theme="default") as demo:
|
| 128 |
+
gr.Markdown(
|
| 129 |
+
"""
|
| 130 |
+
<div style='text-align: center; padding: 1rem;'>
|
| 131 |
+
<h1 style='color: #3b82f6;'>📄 AI-Powered PDF Q&A System</h1>
|
| 132 |
+
<p style='font-size: 1.1rem;'>Upload your PDFs, generate smart questions, and get intelligent answers.</p>
|
| 133 |
+
</div>
|
| 134 |
+
"""
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
with gr.Tab("📤 1. Upload PDF"):
|
| 138 |
+
gr.Markdown("### 🗂 Upload a PDF File")
|
| 139 |
+
file = gr.File(label="Upload one or more PDFs", file_types=[".pdf"], file_count="multiple")
|
| 140 |
+
upload_out = gr.Textbox(label="Upload Result", interactive=False)
|
| 141 |
+
file.change(fn=upload_pdf, inputs=file, outputs=upload_out)
|
| 142 |
+
|
| 143 |
+
with gr.Tab("🧠 2. Generate Questions & Answers"):
|
| 144 |
+
gr.Markdown("### 🤖 Generate Questions and Answers from Uploaded PDF")
|
| 145 |
+
token_input = gr.Textbox(label="🔑 Enter Received Token", placeholder="e.g., 123e4567-e89b-12d3-a456...")
|
| 146 |
+
output_box = gr.Textbox(label="📝 Generated Q&A", lines=15, interactive=False)
|
| 147 |
+
gr.Button("🚀 Generate Q&A").click(fn=generate_qa, inputs=token_input, outputs=output_box)
|
| 148 |
+
|
| 149 |
+
with gr.Tab("❓ 3. Ask a Question"):
|
| 150 |
+
gr.Markdown("### 💬 Ask a question based on uploaded PDF")
|
| 151 |
+
token_box = gr.Textbox(label="Token ID", placeholder="e.g., 123e4567-e89b-12d3-a456...")
|
| 152 |
+
question_box = gr.Textbox(label="Type your question", placeholder="What is the main topic discussed?")
|
| 153 |
+
answer_result = gr.Textbox(label="Answer Output", lines=6, interactive=False)
|
| 154 |
+
gr.Button("🎯 Get Answer").click(fn=ask_question, inputs=[token_box, question_box], outputs=answer_result)
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 158 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|