File size: 5,772 Bytes
74c716c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9523bcf
 
74c716c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9523bcf
 
 
 
 
 
74c716c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# MIT License
#
# Copyright (c) 2023 Victor Calderon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import logging
from typing import Dict, Optional

from datasets import Dataset
from fastapi import Depends, FastAPI
from fastapi.responses import RedirectResponse
from huggingface_hub import hf_hub_download
from pydantic import BaseModel

from src.classes import hugging_face_utils as hf
from src.classes import semantic_search_engine as ss
from src.utils import default_variables as dv
import os
from pathlib import Path

logger = logging.getLogger(__name__)
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s]: %(message)s",
)
logger.setLevel(logging.INFO)


# ------------------------------- VARIABLES -----------------------------------

APP_TITLE = "Cicero LLM Synthesizer"
APP_DESCRIPTION = f"""
The '{APP_TITLE}'is an app that will identify the top-N articles from the
Cicero database that are most similar to the user's input query.
"""
APP_VERSION = "0.1"


# ----------------------------- APP-SPECIFIC ----------------------------------

# Defining the appliation value
app = FastAPI(
    title=APP_TITLE,
    description=APP_DESCRIPTION,
    version=APP_VERSION,
)

# -------------------------------- CLASSES ------------------------------------

# Creating directory
cache_dir = Path(".").resolve().joinpath("cache")
cache_dir.mkdir(exist_ok=True,parents=True,)

os.environ['SENTENCE_TRANSFORMERS_HOME'] = str(cache_dir)


class QueryParams(BaseModel):
    input_query: str
    number_articles: Optional[int] = 5


# ------------------------------- FUNCTIONS -----------------------------------


def download_dataset_and_faiss_index() -> Dataset:
    """
    Function to download the corresponding dataset and the FAISS index
    from HuggingFace.

    Returns
    -------------
    dataset_with_faiss_index : datasets.Dataset
        Dataset from HuggingFace with the FAISS index loaded.
    """
    # --- Initializing HuggingFace API
    # Object for interacting with HuggingFace
    hf_obj = hf.HuggingFaceHelper()

    # Defining variable names for each of the objects
    faiss_index_name = f"{dv.faiss_index_name}.faiss"
    dataset_name = dv.dataset_faiss_embeddings_name
    username = hf_obj.username
    repository_name = dv.hugging_face_repository_name
    repository_id = f"{username}/{repository_name}"
    repository_type = "dataset"
    split_type = "train"

    # --- Downloading FAISS Index
    faiss_index_local_path = hf_hub_download(
        repo_id=repository_id,
        filename=faiss_index_name,
        repo_type=repository_type,
        token=hf_obj.api.token,
    )

    # --- Downloading Dataset
    dataset_obj = hf_obj.get_dataset_from_hub(
        dataset_name=dataset_name,
        username=username,
        split=split_type,
    )

    # --- Adding FAISS index to the dataset
    dataset_obj.load_faiss_index(
        index_name=dv.embeddings_colname,
        file=faiss_index_local_path,
    )

    return dataset_obj


def run_semantic_search_task(query: str, number_articles: int) -> Dict:
    """
    Function to run semantic search on an input query. It will return a
    set of 'Top-N' articles that are most similar to the input query.

    Parameters
    ------------
    query : str
        Input query to use when running the Semantic Search Engine.

    number_articles : int
        Number of articles to return from the Semantic Search.

    Returns
    ----------
    ranked_results : dict
        Dictionary containing the ranked results from the Semantic
        Search Engine.
    """
    # --- Extracting dataset with FAISS index
    corpus_dataset_with_faiss_index = download_dataset_and_faiss_index()

    # --- Initializing Semantic Search Engine
    semantic_search_obj = ss.SemanticSearchEngine(
        corpus_dataset_with_faiss_index=corpus_dataset_with_faiss_index
    )

    # --- Running search on Top-N results

    return semantic_search_obj.run_semantic_search(
        query=query,
        top_n=number_articles,
    )


# -------------------------------- ROUTES -------------------------------------


@app.get("/", include_in_schema=False)
async def docs_redirect():
    return RedirectResponse(url="/docs")


# ---- Semantic Search
@app.post("/predict")
async def run_semantic_search(query_params: QueryParams = Depends()):
    """
    Function to run semantic search on the an input query.

    Parameters
    --------------
    query : str
        Input query to use when running the Semantic Search Engine.

    number_articles : int
        Number of articles to return from the Semantic Search.
    """

    return run_semantic_search_task(
        query=query_params.input_query,
        number_articles=query_params.number_articles,
    )