Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import faiss
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
|
| 8 |
+
embed_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 9 |
+
index = faiss.read_index("faiss_index.bin")
|
| 10 |
+
with open("processed_chunks.json", "r") as f:
|
| 11 |
+
chunks = json.load(f)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
#weights load automatically to the Space
|
| 15 |
+
pipe = pipeline("text-generation", model="ibm-granite/granite-3.1-2b-instruct")
|
| 16 |
+
|
| 17 |
+
def ask_hr_bot(question):
|
| 18 |
+
# Retrieval
|
| 19 |
+
query_vec = embed_model.encode([question])
|
| 20 |
+
distances, indices = index.search(np.array(query_vec).astype('float32'), k=1)
|
| 21 |
+
|
| 22 |
+
# out-of-scope questions
|
| 23 |
+
if distances[0][0] > 1.5:
|
| 24 |
+
return "I could not find information on this in the HR documents.", "N/A"
|
| 25 |
+
|
| 26 |
+
# Context Retrieval
|
| 27 |
+
relevant_chunk = chunks[indices[0][0]]
|
| 28 |
+
context = relevant_chunk['text']
|
| 29 |
+
source = relevant_chunk['doc_name']
|
| 30 |
+
|
| 31 |
+
# Grounded Generation
|
| 32 |
+
prompt = f"Context: {context}\nQuestion: {question}\nAnswer only from context. Cite source: {source}\nAnswer:"
|
| 33 |
+
res = pipe(prompt, max_new_tokens=60, do_sample=False)
|
| 34 |
+
|
| 35 |
+
answer = res[0]['generated_text'].split("Answer:")[-1].strip()
|
| 36 |
+
return answer, source
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
interface = gr.Interface(
|
| 40 |
+
fn=ask_hr_bot,
|
| 41 |
+
inputs=gr.Textbox(label="Ask an HR Question"),
|
| 42 |
+
outputs=[gr.Textbox(label="Bot Answer"), gr.Textbox(label="Source Used")],
|
| 43 |
+
title="ADU HR Knowledge Assistant",
|
| 44 |
+
description="Enterprise RAG Prototype using IBM Granite-3.1-2b"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
interface.launch()
|