|
import urllib.request, json |
|
from transformers.utils import logging |
|
logging.set_verbosity_error() |
|
|
|
from sentence_transformers import SentenceTransformer |
|
from sentence_transformers import util |
|
|
|
|
|
SEARCH_URL = 'https://dd4-biblical.appspot.com/_api/scriptures/v1/search?searchText={}&lang=en&version={}' |
|
STANDARD_VERSION = 'RSKJ' |
|
COMPARISON_VERSION = 'SEP' |
|
|
|
|
|
|
|
|
|
REFERENCES = 'Gen 1' |
|
|
|
|
|
|
|
class Candidate: |
|
compareText = '' |
|
score = 0 |
|
|
|
def __init__(self, book, chapter, verse, standardText): |
|
self.book = book |
|
self.chapter = chapter |
|
self.verse = verse |
|
self.standardText = standardText |
|
|
|
def reference(self): |
|
return '{} {}:{}'.format(self.book, self.chapter, self.verse) |
|
|
|
def __str__(self): |
|
return '{},{:.4f},"{}","{}"'.format(self.reference(), self.score, self.standardText, self.compareText) |
|
|
|
def __repr__(self): |
|
return str(self) |
|
|
|
def compare(model, candidate): |
|
embeddings1 = model.encode(candidate.standardText, convert_to_tensor=True) |
|
|
|
embeddings2 = model.encode(candidate.compareText, convert_to_tensor=True) |
|
|
|
|
|
cosine_scores = util.cos_sim(embeddings1, embeddings2) |
|
|
|
|
|
candidate.score = cosine_scores[0][0] |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
candidates = [] |
|
candidateMap = {} |
|
|
|
with urllib.request.urlopen(SEARCH_URL.format(urllib.parse.quote(REFERENCES), STANDARD_VERSION)) as url: |
|
response = json.load(url) |
|
|
|
|
|
for result in response['items']: |
|
|
|
candidate = Candidate(result['book'], result['chapter'], result['verse'], result['text']) |
|
candidates.append(candidate) |
|
candidateMap[candidate.reference()] = candidate |
|
|
|
|
|
with urllib.request.urlopen(SEARCH_URL.format(urllib.parse.quote(REFERENCES), COMPARISON_VERSION)) as url: |
|
response = json.load(url) |
|
|
|
|
|
for result in response['items']: |
|
|
|
candidate = candidateMap['{} {}:{}'.format(result['book'], result['chapter'], result['verse'])] |
|
if candidate is None : |
|
candidate = Candidate(result['book'], result['chapter'], result['verse'], '') |
|
candidates.append(candidate) |
|
candidateMap[candidate.reference()] = candidate |
|
|
|
candidate.compareText = result['text'] |
|
|
|
model = SentenceTransformer("all-MiniLM-L6-v2") |
|
|
|
for candidate in candidates: |
|
compare(model, candidate) |
|
print(candidate) |