Update User_Specific_Documents.py
Browse files- User_Specific_Documents.py +133 -130
User_Specific_Documents.py
CHANGED
@@ -1,131 +1,134 @@
|
|
1 |
-
import os
|
2 |
-
import gradio as gr
|
3 |
-
from openai import OpenAI
|
4 |
-
import weaviate
|
5 |
-
from weaviate.classes.init import Auth
|
6 |
-
import pypdf # Replaced PyPDF2
|
7 |
-
import docx
|
8 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
9 |
-
from dotenv import load_dotenv
|
10 |
-
from prompt_template import (
|
11 |
-
Prompt_template_translation,
|
12 |
-
Prompt_template_LLM_Generation,
|
13 |
-
Prompt_template_Reranker,
|
14 |
-
Prompt_template_Wisal,
|
15 |
-
Prompt_template_Halluciations,
|
16 |
-
Prompt_template_paraphrasing,
|
17 |
-
Prompt_template_Translate_to_original,
|
18 |
-
Prompt_template_relevance,
|
19 |
-
Prompt_template_User_document_prompt
|
20 |
-
)
|
21 |
-
# βββ Configuration βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
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 |
-
elif ext == ".
|
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 |
demo.launch(debug=True)
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
from openai import OpenAI
|
4 |
+
import weaviate
|
5 |
+
from weaviate.classes.init import Auth
|
6 |
+
import pypdf # Replaced PyPDF2
|
7 |
+
import docx
|
8 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
from prompt_template import (
|
11 |
+
Prompt_template_translation,
|
12 |
+
Prompt_template_LLM_Generation,
|
13 |
+
Prompt_template_Reranker,
|
14 |
+
Prompt_template_Wisal,
|
15 |
+
Prompt_template_Halluciations,
|
16 |
+
Prompt_template_paraphrasing,
|
17 |
+
Prompt_template_Translate_to_original,
|
18 |
+
Prompt_template_relevance,
|
19 |
+
Prompt_template_User_document_prompt
|
20 |
+
)
|
21 |
+
# βββ Configuration βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
22 |
+
GEMINI_API_KEY="AIzaSyCUCivstFpC9pq_jMHMYdlPrmh9Bx97dFo"
|
23 |
+
TAVILY_API_KEY="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"
|
24 |
+
OPENAI_API_KEY="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"
|
25 |
+
QDRANT_API_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIiwiZXhwIjoxNzUxMDUxNzg4fQ.I9J-K7OM0BtcNKgj2d4uVM8QYAHYfFCVAyP4rlZkK2E"
|
26 |
+
QDRANT_URL="https://6a3aade6-e8ad-4a6c-a579-21f5af90b7e8.us-east4-0.gcp.cloud.qdrant.io"
|
27 |
+
OPENAI_API_KEY="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"
|
28 |
+
WEAVIATE_URL="https://xbvlj5rpqyiswspww0tthq.c0.us-west3.gcp.weaviate.cloud"
|
29 |
+
WEAVIATE_API_KEY="RU9acU1CYnNRTjY1S1ZFc18zNS9tQktaWlcwTzFEUjlscEVCUGF4YU5xRWx2MDhmTUtIdUhnOWdOTGVZPV92MjAw"
|
30 |
+
DEEPINFRA_API_KEY="285LUJulGIprqT6hcPhiXtcrphU04FG4"
|
31 |
+
DEEPINFRA_BASE_URL="https://api.deepinfra.com/v1/openai"
|
32 |
+
|
33 |
+
openai = OpenAI(
|
34 |
+
api_key=DEEPINFRA_TOKEN,
|
35 |
+
base_url="https://api.deepinfra.com/v1/openai",
|
36 |
+
)
|
37 |
+
# Initialize Weaviate client
|
38 |
+
client = weaviate.connect_to_weaviate_cloud(
|
39 |
+
cluster_url=WEAVIATE_URL,
|
40 |
+
auth_credentials=Auth.api_key(WEAVIATE_API_KEY),
|
41 |
+
)
|
42 |
+
# βββ Utility: Extract raw text ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
43 |
+
def extract_text(file_path: str) -> str:
|
44 |
+
ext = os.path.splitext(file_path)[1].lower()
|
45 |
+
if ext == ".pdf":
|
46 |
+
text = ""
|
47 |
+
with open(file_path, "rb") as f:
|
48 |
+
reader = pypdf.PdfReader(f)
|
49 |
+
for page in reader.pages:
|
50 |
+
page_text = page.extract_text() or ""
|
51 |
+
text += page_text + "\n"
|
52 |
+
elif ext == ".docx":
|
53 |
+
doc = docx.Document(file_path)
|
54 |
+
text = "\n".join(p.text for p in doc.paragraphs)
|
55 |
+
elif ext == ".txt":
|
56 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
57 |
+
text = f.read()
|
58 |
+
else:
|
59 |
+
raise ValueError("Unsupported file format. Use PDF, DOCX, or TXT.")
|
60 |
+
return text
|
61 |
+
# βββ Chunker & Embed ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
62 |
+
splitter = RecursiveCharacterTextSplitter(
|
63 |
+
chunk_size=1000,
|
64 |
+
chunk_overlap=200,
|
65 |
+
separators=["\n\n", "\n", " "],
|
66 |
+
)
|
67 |
+
def embed_texts(texts: list[str], batch_size: int = 70) -> list[list[float]]:
|
68 |
+
"""Embed texts in batches to avoid API limits."""
|
69 |
+
all_embeddings = []
|
70 |
+
for i in range(0, len(texts), batch_size):
|
71 |
+
batch = texts[i:i + batch_size]
|
72 |
+
resp = openai.embeddings.create(
|
73 |
+
model="Qwen/Qwen3-Embedding-8B",
|
74 |
+
input=batch,
|
75 |
+
encoding_format="float"
|
76 |
+
)
|
77 |
+
all_embeddings.extend([item.embedding for item in resp.data])
|
78 |
+
return all_embeddings
|
79 |
+
# βββ Ingest & Index βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
80 |
+
def ingest_file(file_path: str) -> str:
|
81 |
+
raw = extract_text(file_path)
|
82 |
+
docs = splitter.split_text(raw)
|
83 |
+
texts = [chunk for chunk in docs]
|
84 |
+
vectors = embed_texts(texts)
|
85 |
+
# Get the collection
|
86 |
+
documents = client.collections.get("Book")
|
87 |
+
# Batch insert with new API
|
88 |
+
with client.batch.dynamic() as batch:
|
89 |
+
for txt, vec in zip(texts, vectors):
|
90 |
+
batch.add_object(
|
91 |
+
collection="Book",
|
92 |
+
properties={"text": txt},
|
93 |
+
vector=vec
|
94 |
+
)
|
95 |
+
return f"Ingested {len(texts)} chunks from {os.path.basename(file_path)}"
|
96 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ Query & Answer βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
97 |
+
def answer_question(question: str) -> str:
|
98 |
+
q_vec = embed_texts([question])[0]
|
99 |
+
documents = client.collections.get("Book")
|
100 |
+
response = documents.query.near_vector(
|
101 |
+
near_vector=q_vec,
|
102 |
+
limit=5,
|
103 |
+
return_metadata=["distance"]
|
104 |
+
)
|
105 |
+
hits = response.objects
|
106 |
+
context = "\n\n".join(hit.properties["text"] for hit in hits)
|
107 |
+
print(context)
|
108 |
+
|
109 |
+
UserSpecificDocument_prompt = Prompt_template_User_document_prompt.format(new_query=question, document=context)
|
110 |
+
chat = openai.chat.completions.create(
|
111 |
+
model="Qwen/Qwen3-32B",
|
112 |
+
messages=[
|
113 |
+
{"role": "user", "content": UserSpecificDocument_prompt
|
114 |
+
}
|
115 |
+
],
|
116 |
+
temperature=0,
|
117 |
+
reasoning_effort="none"
|
118 |
+
)
|
119 |
+
return chat.choices[0].message.content
|
120 |
+
# βββ Gradio Interface βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
121 |
+
with gr.Blocks(title="Document Q&A with Qwen & Weaviate") as demo:
|
122 |
+
gr.Markdown("## Upload a PDF, DOCX, or TXT and then ask away!")
|
123 |
+
with gr.Row():
|
124 |
+
up = gr.File(label="Select document")
|
125 |
+
btn = gr.Button("Ingest")
|
126 |
+
out = gr.Textbox(label="Status", interactive=False)
|
127 |
+
btn.click(fn=lambda f: ingest_file(f.name), inputs=up, outputs=out)
|
128 |
+
with gr.Row():
|
129 |
+
q = gr.Textbox(placeholder="Your question...", lines=2)
|
130 |
+
ask = gr.Button("Ask")
|
131 |
+
ans = gr.Textbox(label="Answer", lines=6, interactive=False)
|
132 |
+
ask.click(fn=answer_question, inputs=q, outputs=ans)
|
133 |
+
if __name__ == "__main__":
|
134 |
demo.launch(debug=True)
|