Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import random
|
| 3 |
+
import time
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
import pinecone
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
retriever = SentenceTransformer("sentence-transformers/all-MiniLM-L12-v2")
|
| 9 |
+
|
| 10 |
+
pinecone_key = os.environ['PINECONE_SECRET']
|
| 11 |
+
|
| 12 |
+
pinecone.init(
|
| 13 |
+
api_key=os.environ['PINECONE_SECRET'],
|
| 14 |
+
environment="eu-west1-gcp"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
index_name = 'quran-ayah-search'
|
| 18 |
+
|
| 19 |
+
index = pinecone.Index(index_name)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def query_pinecone(query, top_k):
|
| 23 |
+
xq = retriever.encode([query]).tolist()
|
| 24 |
+
|
| 25 |
+
# search vector database for similar vector
|
| 26 |
+
xc = index.query(xq, top_k=top_k, include_metadata=True)
|
| 27 |
+
|
| 28 |
+
return xc['matches']
|
| 29 |
+
|
| 30 |
+
def format_search_result(result):
|
| 31 |
+
data = result['metadata']
|
| 32 |
+
message = f"Ayah no: {data['ayah']}\nSurah no: {data['surah']}\nSentence:{data['arabic-text']}\nTranslation: {data['en-translation']}\n Tafsir:{data['en-tafsir-mokhtasar']}\n Relevant Tafsir: {data['vector-chunk']}"
|
| 33 |
+
|
| 34 |
+
return message
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
with gr.Blocks() as demo:
|
| 38 |
+
chatbot = gr.Chatbot()
|
| 39 |
+
msg = gr.Textbox()
|
| 40 |
+
clear = gr.Button("Clear")
|
| 41 |
+
|
| 42 |
+
def user(user_message, history):
|
| 43 |
+
return "", history + [[user_message, None]]
|
| 44 |
+
|
| 45 |
+
def bot(history):
|
| 46 |
+
|
| 47 |
+
query = history[-1][0]
|
| 48 |
+
|
| 49 |
+
results = query_pinecone(query, top_k=3)
|
| 50 |
+
|
| 51 |
+
for match in results:
|
| 52 |
+
if history[-1][1] == None:
|
| 53 |
+
history[-1][1] = format_search_result(match)
|
| 54 |
+
|
| 55 |
+
else:
|
| 56 |
+
history.append([None, format_search_result(match)])
|
| 57 |
+
|
| 58 |
+
return history
|
| 59 |
+
|
| 60 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 61 |
+
bot, chatbot, chatbot
|
| 62 |
+
)
|
| 63 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
demo.launch()
|