Spaces:
Runtime error
Runtime error
muhalmutaz
commited on
Commit
•
b7a035e
1
Parent(s):
8e1c44a
app
Browse files- app.py +53 -0
- quran-simple-clean.txt +0 -0
- tafsir-simple-clean.txt +0 -0
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder, util
|
2 |
+
import torch
|
3 |
+
import pickle
|
4 |
+
import pandas as pd
|
5 |
+
import gradio as gr
|
6 |
+
|
7 |
+
# bi_encoder = SentenceTransformer("microsoft/Multilingual-MiniLM-L12-H384")
|
8 |
+
cross_encoder = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1")
|
9 |
+
# Corpus from quran
|
10 |
+
my_file = open("quran-simple-clean.txt", "r",encoding="utf-8")
|
11 |
+
data = my_file.read()
|
12 |
+
quran = data.split("\n")
|
13 |
+
my_file = open("tafsir-simple-clean.txt", "r",encoding="utf-8")
|
14 |
+
data = my_file.read()
|
15 |
+
corpus = data.split("\n")
|
16 |
+
del data
|
17 |
+
embedder = SentenceTransformer('symanto/sn-xlm-roberta-base-snli-mnli-anli-xnli')
|
18 |
+
corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True)
|
19 |
+
|
20 |
+
def search(query,top_k=100):
|
21 |
+
print("New query:")
|
22 |
+
print(query)
|
23 |
+
ans=[]
|
24 |
+
##### Sematic Search #####
|
25 |
+
# Encode the query using the bi-encoder and find potentially relevant passages
|
26 |
+
question_embedding = embedder.encode(query, convert_to_tensor=True)
|
27 |
+
hits = util.semantic_search(question_embedding, corpus_embeddings, top_k=top_k)
|
28 |
+
hits = hits[0] # Get the hits for the first query
|
29 |
+
|
30 |
+
##### Re-Ranking #####
|
31 |
+
# Now, score all retrieved passages with the cross_encoder
|
32 |
+
cross_inp = [[query, corpus[hit['corpus_id']]] for hit in hits]
|
33 |
+
cross_scores = cross_encoder.predict(cross_inp)
|
34 |
+
|
35 |
+
# Sort results by the cross-encoder scores
|
36 |
+
for idx in range(len(cross_scores)):
|
37 |
+
hits[idx]['cross-score'] = cross_scores[idx]
|
38 |
+
|
39 |
+
hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True)
|
40 |
+
|
41 |
+
for idx, hit in enumerate(hits[0:5]):
|
42 |
+
ans.append(quran[hit['corpus_id']])
|
43 |
+
return "\n\n".join(ans)
|
44 |
+
|
45 |
+
exp=[""]
|
46 |
+
|
47 |
+
desc="هذا البحث يعتمد على تفسير السعدي في البحث."
|
48 |
+
|
49 |
+
inp=gr.inputs.Textbox(lines=1, placeholder=None, default="", label="أدخل كلمات البحث هنا")
|
50 |
+
out=gr.outputs.Textbox(type="auto",label="نتائج البحث")
|
51 |
+
|
52 |
+
iface = gr.Interface(fn=search, inputs=inp, outputs=out,examples=exp,article=desc,title="البحث في معاني تفسير السعدي")
|
53 |
+
iface.launch(share=True)
|
quran-simple-clean.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tafsir-simple-clean.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|