bkbilal09 commited on
Commit
eb7d944
Β·
verified Β·
1 Parent(s): c0ce8e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -36
app.py CHANGED
@@ -9,14 +9,11 @@ from langchain_groq import ChatGroq
9
  from langchain_core.prompts import PromptTemplate
10
  from langchain_classic.chains import RetrievalQA
11
 
12
- # Suppress unnecessary logs
13
  warnings.filterwarnings("ignore")
14
 
15
  # --- CONFIGURATION ---
16
- # Ensure you have 'MY_GROQ_KEY' in your HF Space Secrets
17
  GROQ_API_KEY = os.environ.get("MY_GROQ_KEY")
18
-
19
- # High-quality embedding model (Runs on CPU)
20
  embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")
21
  rag_chain = None
22
 
@@ -26,47 +23,30 @@ def build_rag_system(file):
26
  if not GROQ_API_KEY: return "❌ Error: Groq API Key missing in Secrets!"
27
 
28
  try:
29
- # Load PDF or TXT
30
  loader = PyPDFLoader(file.name) if file.name.endswith(".pdf") else TextLoader(file.name)
31
  documents = loader.load()
32
-
33
- # Split into chunks
34
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=80)
35
  texts = text_splitter.split_documents(documents)
36
-
37
- # Create Vector Store
38
  vector_db = FAISS.from_documents(texts, embeddings)
39
  retriever = vector_db.as_retriever(search_kwargs={"k": 3})
40
 
41
- # Initialize Groq Llama 3.3
42
- llm = ChatGroq(
43
- groq_api_key=GROQ_API_KEY,
44
- model_name="llama-3.3-70b-versatile",
45
- temperature=0
46
- )
47
 
48
- # Strict Prompting
49
- template = """You are a professional assistant. Answer ONLY using the context.
50
- If the answer is not there, say: "I don't have enough information about this in the provided documents."
51
 
52
  Context: {context}
53
  Question: {question}
54
  Answer:"""
55
 
56
  QA_PROMPT = PromptTemplate.from_template(template)
57
- rag_chain = RetrievalQA.from_chain_type(
58
- llm=llm,
59
- retriever=retriever,
60
- chain_type_kwargs={"prompt": QA_PROMPT}
61
- )
62
-
63
- return "βœ… Document Vault Successfully Built!"
64
  except Exception as e:
65
  return f"❌ System Error: {str(e)}"
66
 
67
  def predict(message, history):
68
- if rag_chain is None:
69
- return "Please upload a document and click Build first."
70
  try:
71
  res = rag_chain.invoke({"query": message})
72
  return res["result"]
@@ -74,25 +54,33 @@ def predict(message, history):
74
  return f"🚨 API ERROR: {str(e)}"
75
 
76
  # --- PROFESSIONAL UI DESIGN ---
77
- # Removed 'type="messages"' to fix the deployment error
78
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="VerityVault AI") as demo:
79
- gr.Markdown("# πŸ›‘οΈ VerityVault AI")
80
- gr.Markdown("### Developed by: **Bilal**")
81
- gr.Markdown("*Secure document intelligence with zero hallucinations.*")
 
 
 
82
 
83
  with gr.Row():
84
  with gr.Column(scale=1):
85
- file_input = gr.File(label="πŸ“„ Source Document", file_types=[".pdf", ".txt"])
86
- build_btn = gr.Button("πŸš€ BUILD VAULT", variant="primary")
87
  status = gr.Textbox(label="Vault Status", interactive=False)
88
 
89
  with gr.Column(scale=2):
90
  gr.ChatInterface(
91
  fn=predict,
92
- description="The vault will only answer based on your uploaded file."
93
  )
94
 
95
- build_btn.click(build_rag_system, inputs=[file_input], outputs=[status])
 
 
 
 
 
96
 
97
  if __name__ == "__main__":
98
  demo.launch()
 
9
  from langchain_core.prompts import PromptTemplate
10
  from langchain_classic.chains import RetrievalQA
11
 
12
+ # Suppress logs
13
  warnings.filterwarnings("ignore")
14
 
15
  # --- CONFIGURATION ---
 
16
  GROQ_API_KEY = os.environ.get("MY_GROQ_KEY")
 
 
17
  embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")
18
  rag_chain = None
19
 
 
23
  if not GROQ_API_KEY: return "❌ Error: Groq API Key missing in Secrets!"
24
 
25
  try:
 
26
  loader = PyPDFLoader(file.name) if file.name.endswith(".pdf") else TextLoader(file.name)
27
  documents = loader.load()
 
 
28
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=80)
29
  texts = text_splitter.split_documents(documents)
 
 
30
  vector_db = FAISS.from_documents(texts, embeddings)
31
  retriever = vector_db.as_retriever(search_kwargs={"k": 3})
32
 
33
+ llm = ChatGroq(groq_api_key=GROQ_API_KEY, model_name="llama-3.3-70b-versatile", temperature=0)
 
 
 
 
 
34
 
35
+ template = """Answer ONLY using the context. If not found, say:
36
+ "I don't have enough information about this in the provided documents."
 
37
 
38
  Context: {context}
39
  Question: {question}
40
  Answer:"""
41
 
42
  QA_PROMPT = PromptTemplate.from_template(template)
43
+ rag_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever, chain_type_kwargs={"prompt": QA_PROMPT})
44
+ return "βœ… Vault Verified & Locked!"
 
 
 
 
 
45
  except Exception as e:
46
  return f"❌ System Error: {str(e)}"
47
 
48
  def predict(message, history):
49
+ if rag_chain is None: return "Please upload a document first."
 
50
  try:
51
  res = rag_chain.invoke({"query": message})
52
  return res["result"]
 
54
  return f"🚨 API ERROR: {str(e)}"
55
 
56
  # --- PROFESSIONAL UI DESIGN ---
57
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="slate", radius_size="lg"), title="VerityVault AI") as demo:
58
+ gr.Markdown(
59
+ """
60
+ # πŸ›‘οΈ VerityVault AI
61
+ ### Developed by: **Bilal**
62
+ *Grounded document intelligence with zero hallucinations.*
63
+ """
64
+ )
65
 
66
  with gr.Row():
67
  with gr.Column(scale=1):
68
+ file_input = gr.File(label="πŸ“„ Deposit Document (PDF/TXT)")
69
+ build_btn = gr.Button("πŸ”’ INITIALIZE VAULT", variant="primary")
70
  status = gr.Textbox(label="Vault Status", interactive=False)
71
 
72
  with gr.Column(scale=2):
73
  gr.ChatInterface(
74
  fn=predict,
75
+ description="The vault only answers using your verified data."
76
  )
77
 
78
+ # CRITICAL: This must be indented inside the 'with gr.Blocks' block!
79
+ build_btn.click(
80
+ fn=build_rag_system,
81
+ inputs=[file_input],
82
+ outputs=[status]
83
+ )
84
 
85
  if __name__ == "__main__":
86
  demo.launch()