File size: 6,631 Bytes
0206245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5811ef8
0206245
6fda7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0206245
6fda7e6
 
5811ef8
 
 
 
0206245
677f8bc
0206245
 
 
 
 
 
5811ef8
0206245
 
5811ef8
0206245
5811ef8
 
 
0206245
 
 
5811ef8
0206245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5811ef8
 
 
 
 
 
 
 
0206245
5811ef8
0206245
 
 
 
 
5811ef8
0206245
5811ef8
0206245
 
 
 
 
 
 
5811ef8
0206245
 
 
5811ef8
0206245
5811ef8
0206245
5811ef8
0206245
 
 
5811ef8
0206245
5811ef8
 
0206245
5811ef8
 
0206245
 
 
5811ef8
0206245
 
5811ef8
0206245
 
5811ef8
0206245
 
 
 
5811ef8
 
0206245
 
 
 
 
 
 
 
5811ef8
0206245
 
 
 
 
 
 
 
33760b3
 
 
0206245
5811ef8
0206245
 
 
 
5811ef8
0206245
33760b3
 
0206245
33760b3
0206245
33760b3
 
 
 
 
 
 
5811ef8
0206245
 
 
5811ef8
0206245
 
 
5811ef8
 
 
0206245
5811ef8
 
 
 
 
 
 
 
 
0206245
 
5811ef8
 
0206245
5811ef8
0206245
5811ef8
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import os
import re
import time
import gdown
import gradio as gr

from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

# ==========================================
# 1. GROQ API KEY CONFIGURATION
# ==========================================
# ==========================================
# GROQ API KEY CONFIGURATION (For HF Spaces Only)
# ==========================================
print("πŸ”‘ Checking GROQ API Key...")

GROQ_API_KEY = os.getenv("GROQ_API_KEY")

if not GROQ_API_KEY:
    print("⚠️ No GROQ_API_KEY found in environment variables")

if not GROQ_API_KEY:
    raise ValueError("""
    ❌ GROQ_API_KEY is missing!
    
    Please go to:
    Space Settings β†’ Secrets 
    
    and add:
    Key   : GROQ_API_KEY
    Value : your_actual_groq_api_key_here
    """)

os.environ["GROQ_API_KEY"] = GROQ_API_KEY
print("βœ… GROQ API Key loaded successfully!")

# ==========================================
# 2. CONFIGURATION
# ==========================================
links_to_process = [
    "https://drive.google.com/file/d/1rb7AeJZrDNR-bq8Q9V4IvtzYZsDOvDH0/view?usp=sharing"
]

output_dir = 'knowledge_base'
os.makedirs(output_dir, exist_ok=True)

# ==========================================
# 3. HELPER: EXTRACT GOOGLE DRIVE FILE ID
# ==========================================
def extract_file_id(url):
    """Extract file ID from Google Drive links"""
    match = re.search(r'/d/([a-zA-Z0-9_-]+)', url)
    if match:
        return match.group(1)
    match = re.search(r'id=([a-zA-Z0-9_-]+)', url)
    return match.group(1) if match else None

# ==========================================
# 4. BUILD VECTOR DATABASE
# ==========================================
def build_vector_db(links):
    print(f"πŸ“₯ Starting download of {len(links)} documents...")

    downloaded_files = 0

    for link in links:
        try:
            file_id = extract_file_id(link)
            if not file_id:
                print(f"⚠️ Invalid link: {link}")
                continue

            direct_url = f"https://drive.google.com/uc?id={file_id}"
            output_path = os.path.join(output_dir, f"{file_id}.pdf")

            print(f"πŸ“„ Downloading: {file_id}")
            
            gdown.download(
                url=direct_url,
                output=output_path,
                quiet=True,
                use_cookies=False
            )
            
            downloaded_files += 1
            time.sleep(1.5)

        except Exception as e:
            print(f"❌ Failed to download {link}: {e}")

    if downloaded_files == 0:
        raise ValueError("❌ No files downloaded. Check sharing settings ('Anyone with the link')")

    # Load PDFs
    all_docs = []
    for filename in os.listdir(output_dir):
        if filename.endswith(".pdf"):
            file_path = os.path.join(output_dir, filename)
            try:
                loader = PyPDFLoader(file_path)
                all_docs.extend(loader.load())
                print(f"βœ… Loaded: {filename}")
            except Exception as e:
                print(f"⚠️ Error loading {filename}: {e}")

    print(f"βœ… Total PDFs loaded: {len(all_docs)}")

    # Text Splitting
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=800,
        chunk_overlap=100
    )
    chunks = text_splitter.split_documents(all_docs)
    print(f"🧩 Created {len(chunks)} chunks.")

    # Embeddings & Vector Store
    embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
    vector_db = FAISS.from_documents(chunks, embeddings)
    
    print("πŸŽ‰ Vector Database Created Successfully!")
    return vector_db

# ==========================================
# 5. INITIALIZE RAG SYSTEM
# ==========================================
vector_store = build_vector_db(links_to_process)
retriever = vector_store.as_retriever(search_kwargs={"k": 4})

llm = ChatGroq(
    model="llama-3.1-8b-instant",
    temperature=0.3,
    max_tokens=1024
)

prompt_template = """Answer the question professionally and accurately based ONLY on the context below.
If the answer is not in the context, say "I don't have enough information from the provided documents."

Context:
{context}

Question: {question}

Answer:"""

prompt = ChatPromptTemplate.from_template(prompt_template)

rag_chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

# ==========================================
# 6. GRADIO INTERFACE
# ==========================================
# ==========================================
# 6. GRADIO INTERFACE
# ==========================================
def process_query(query):
    if not query or not query.strip():
        return "**Please enter a question.**"
    
    try:
        print(f"πŸ” Processing query: {query[:80]}...")   # For debugging
        result = rag_chain.invoke(query)
        return result
    
    except Exception as e:
        error_str = str(e).lower()
        if "rate limit" in error_str or "429" in error_str:
            return "⚠️ **Rate limit reached.** Please wait 20-30 seconds and try again."
        elif "api key" in error_str:
            return "❌ API Key issue. Please check GROQ_API_KEY in Secrets."
        else:
            return f"❌ Error: {str(e)}"


# Custom CSS
custom_css = """
.gradio-container { max-width: 1000px; margin: auto; }
"""

with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.Markdown("# πŸ›οΈ **DocMind Intelligence**")
    gr.Markdown("### Multi-Document RAG System | Powered by Groq + LangChain")
    
    with gr.Row():
        query_input = gr.Textbox(
            label="Ask your question",
            placeholder="Type your question here about the uploaded documents...",
            lines=3
        )
    
    with gr.Row():
        submit_btn = gr.Button("πŸš€ Get Answer", variant="primary", size="large")
    
    output = gr.Markdown(label="Response", value="_Waiting for your question..._")

    submit_btn.click(process_query, inputs=query_input, outputs=output)
    query_input.submit(process_query, inputs=query_input, outputs=output)

    gr.Markdown("---\n**Tip:** Be clear and specific in your questions for best results.")

demo.launch()