Delete rag_pipeline.py
Browse files- rag_pipeline.py +0 -57
rag_pipeline.py
DELETED
|
@@ -1,57 +0,0 @@
|
|
| 1 |
-
import pandas as pd
|
| 2 |
-
import faiss
|
| 3 |
-
import numpy as np
|
| 4 |
-
from langdetect import detect
|
| 5 |
-
from sentence_transformers import SentenceTransformer
|
| 6 |
-
from transformers import MBartForConditionalGeneration, MBart50TokenizerFast
|
| 7 |
-
import zipfile
|
| 8 |
-
import os
|
| 9 |
-
|
| 10 |
-
# Extract zip if needed
|
| 11 |
-
zip_file = "all_languages_test.csv.zip"
|
| 12 |
-
csv_file = "all_languages_test.csv"
|
| 13 |
-
|
| 14 |
-
if not os.path.exists(csv_file):
|
| 15 |
-
with zipfile.ZipFile(zip_file, "r") as zip_ref:
|
| 16 |
-
zip_ref.extractall()
|
| 17 |
-
|
| 18 |
-
# Translation model
|
| 19 |
-
tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
|
| 20 |
-
model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
|
| 21 |
-
|
| 22 |
-
lang_map = {
|
| 23 |
-
"en": "en_XX", "fr": "fr_XX", "ur": "ur_PK", "hi": "hi_IN",
|
| 24 |
-
"es": "es_XX", "de": "de_DE", "zh-cn": "zh_CN", "ar": "ar_AR"
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
@st.cache_resource
|
| 28 |
-
def load_index():
|
| 29 |
-
df = pd.read_csv("all_languages_test.csv").dropna()
|
| 30 |
-
df["context"] = df["premise"] + " " + df["hypothesis"]
|
| 31 |
-
corpus = df["context"].tolist()
|
| 32 |
-
|
| 33 |
-
embedder = SentenceTransformer("distiluse-base-multilingual-cased-v2")
|
| 34 |
-
embeddings = embedder.encode(corpus, show_progress_bar=True)
|
| 35 |
-
|
| 36 |
-
index = faiss.IndexFlatL2(embeddings.shape[1])
|
| 37 |
-
index.add(np.array(embeddings))
|
| 38 |
-
|
| 39 |
-
return embedder, index, corpus
|
| 40 |
-
|
| 41 |
-
def generate_answer(query, k=3):
|
| 42 |
-
lang = detect(query)
|
| 43 |
-
token_lang = lang_map.get(lang, "en_XX")
|
| 44 |
-
|
| 45 |
-
embedder, index, corpus = load_index()
|
| 46 |
-
|
| 47 |
-
query_vec = embedder.encode([query])
|
| 48 |
-
D, I = index.search(np.array(query_vec), k)
|
| 49 |
-
contexts = [corpus[i] for i in I[0]]
|
| 50 |
-
context = " ".join(contexts)
|
| 51 |
-
|
| 52 |
-
full_input = f"question: {query} context: {context}"
|
| 53 |
-
tokenizer.src_lang = token_lang
|
| 54 |
-
encoded_input = tokenizer(full_input, return_tensors="pt")
|
| 55 |
-
generated_tokens = model.generate(**encoded_input, forced_bos_token_id=tokenizer.lang_code_to_id[token_lang])
|
| 56 |
-
|
| 57 |
-
return tokenizer.decode(generated_tokens[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|