probahoni_plus / src /prediction.py
istiak101's picture
Update src/prediction.py
69f1dd8 verified
Raw History Blame Contribute Delete
3.81 kB
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, AutoConfig
from textwrap import dedent
from build_db_index import query_vectorstore
from langdetect import detect
from huggingface_hub import login
import subprocess
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
subprocess.run(["huggingface-cli", "login", "--token", huggingface_token], capture_output=True)
class Prediction:
def __init__(self, model_name="istiak101/Qwen1.5-1.8B-Chat-finetunedv1.0"):
"""
Initialize the Prediction class with a model name.
Args:
model_name (str): The name of the model to be used for predictions.
"""
self.model_name = model_name
self.configure_model(model_name)
def create_test_prompt(self, data_row):
prompt = dedent(
f"""
{data_row["question"]}
Information:
```
{data_row["context"]}
```
"""
)
messages = [
{
"role": "system",
"content": "Use only the information to answer the question",
},
{"role": "user", "content": prompt},
]
return self.tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
def detect_language(self, text):
try:
lang = detect(text)
return "bn" if lang == "bn" else "en"
except Exception as e:
print(f"Error detecting language: {e}")
return "en"
def predict(self, query):
pipe = pipeline(
task="text-generation",
model=self.model,
tokenizer=self.tokenizer,
max_new_tokens=400,
return_full_text=False,
temperature=0.8,
top_k=50,
top_p=0.95
)
if self.detect_language(query) == "bn":
context = query_vectorstore(
query=query,
path="vectorstore_bn_recursive",
top_k=1
)
else:
context = query_vectorstore(
query=query,
path="vectorstore_en_recursive",
top_k=1
)
prompt = self.create_test_prompt({"question": query, "context": context})
outputs = pipe(prompt)
prediction = outputs[0]["generated_text"]
prediction = prediction.replace("<|end|>", "").strip()
return prediction
def configure_model(self, model_name):
config = AutoConfig.from_pretrained(model_name)
config.model_type = "qwen2"
self.model = AutoModelForCausalLM.from_pretrained(model_name, config=config)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
# self.tokenizer.chat_template = """{% for message in messages %}
# {% if message['role'] == 'system' -%}
# <|system|>
# {{ message['content'] }}
# <|end|>
# {% elif message['role'] == 'user' -%}
# <|user|>
# {{ message['content'] }}
# <|end|>
# {% elif message['role'] == 'assistant' -%}
# <|assistant|>
# {{ message['content'] }}
# <|end|>
# {% endif %}
# {% endfor -%}
# {% if add_generation_prompt %}
# <|assistant|>
# {% endif %}
# """
PAD_TOKEN = "<|pad|>"
self.tokenizer.add_special_tokens({"pad_token": PAD_TOKEN})
self.tokenizer.padding_side = "right"